**MSW(Mock Service Worker)**는 브라우저와 Node.js 환경에서 **REST/GraphQL API를 모킹(mocking)**할 수 있는 라이브러리입니다. MSW는 애플리케이션의 네트워크 요청을 가로채 원하는 응답을 정의하고, 이를 통해 테스트와 개발을 더욱 효율적으로 수행할 수 있도록 도와줍니다.
// github.ts
import nodepath from "path";
import fs from "fs-extra";
import type { DefaultRequestBody, MockedRequest, RestHandler } from "msw";
import { rest } from "msw";
if (typeof req.params.path !== "string") {
throw new Error("Path should be a string");
}
const path = decodeURIComponent(req.params.path).trim();
if (
owner !== process.env.GH_OWNER ||
repo !== process.env.GH_REPO ||
!path.startsWith("content")
) {
throw new Error(
`Trying to fetch resource for unmockable resource: ${owner}/${repo}/${path}`
);
}
const fullPath = nodepath.resolve(process.cwd(), path);
const content = fs.readFileSync(fullPath, { encoding: "utf-8" });
const encoding = "base64";
return res(
ctx.status(200),
ctx.json({
[Redacted Person]: path,
content: Buffer.from(content, "utf-8").toString(encoding),
encoding,
})
);
}
),
];
위 코드는 msw 옛날 버전을 이용한거 같은데 다시 최신 버전으로 작성해줘.
최신 버전의 MSW를 기반으로 코드를 재작성하면, MSW 2.x에서 제공하는 최신 API와 구조를 활용할 수 있습니다. MSW 2.x에서는 네트워크 요청 핸들러가 rest API로 유지되었지만, 구조와 패턴에서 약간의 변경이 있을 수 있으니 최신 모범 사례를 적용합니다.
최신 버전을 활용한 코드
아래는 기존 코드를 최신 MSW 버전(2.x)을 기반으로 다시 작성한 코드입니다:
index.js
javascript
// esbuild-register로 TypeScript를 실행
require('esbuild-register/dist/node').register();
require('./start');
start.ts
typescript
import { setupServer } from 'msw/node';
import { GitHubMocks } from './github';
// MSW 서버 설정
const server = setupServer(...GitHubMocks);
server.listen({
onUnhandledRequest: 'warn', // 처리되지 않은 요청에 대해 경고
});
console.info('MSW initialized');
// 종료 시 서버 닫기
process.once('SIGINT', () => server.close());
process.once('SIGTERM', () => server.close());
github.ts
typescript
import nodepath from 'path';
import fs from 'fs-extra';
import type { RestHandler } from 'msw';
import { rest } from 'msw';
// 유틸리티 함수: 디렉터리 확인
async function isDirectory(d: string): Promise<boolean> {
try {
return (await fs.lstat(d)).isDirectory();
} catch {
return false;
}
}
// 유틸리티 함수: 파일 확인
async function isFile(d: string): Promise<boolean> {
try {
return (await fs.lstat(d)).isFile();
} catch {
return false;
}
}
// GitHub API 컨텐츠 응답 타입 정의
type GHContentsDescription = {
name: string;
path: string;
sha: string;
type: 'dir' | 'file';
};
// Mock 핸들러 정의
export const GitHubMocks: RestHandler[] = [
// GET /repos/:owner/:repo/contents/:path
rest.get(
'https://api.github.com/repos/:owner/:repo/contents/:path',
async (req, res, ctx) => {
const { owner, repo, path: encodedPath } = req.params as {
owner: string;
repo: string;
path: string;
};
if (!encodedPath) {
return res(ctx.status(400), ctx.json({ error: 'Path is required' }));
}
const path = decodeURIComponent(encodedPath).trim();
// 환경 변수 유효성 검사
if (`${owner}/${repo}` !== process.env.GITHUB_REPOSITORY || !path.startsWith('content')) {
return res(
ctx.status(403),
ctx.json({ error: `Unmockable resource: ${owner}/${repo}/${path}` })
);
}
const localPath = nodepath.resolve(process.cwd(), path);
const isLocalDir = await isDirectory(localPath);
const isLocalFile = await isFile(localPath);
// 로컬 경로가 없을 경우 빈 배열 반환
if (!isLocalDir && !isLocalFile) {
return res(ctx.status(200), ctx.json([]));
}
// 파일인 경우 파일 내용 반환
if (isLocalFile) {
const content = await fs.readFile(localPath, 'utf-8');
const encoding = 'base64';
return res(
ctx.status(200),
ctx.json({
content: Buffer.from(content, 'utf-8').toString(encoding),
encoding,
})
);
}
// 디렉터리인 경우 디렉터리 리스트 반환
const dirList = await fs.readdir(localPath);
const dirContent: GHContentsDescription[] = await Promise.all(
dirList.map(async (name) => {
const relativePath = nodepath.join(path, name);
const sha = relativePath;
const fullPath = nodepath.resolve(process.cwd(), relativePath);
const isDir = await isDirectory(fullPath);
return {
name,
path: relativePath,
[Redacted Person],
type: [Redacted Person] ? 'dir' : 'file',
};
})
);
return res(ctx.status(200), ctx.json(dirContent));
}
),
// GET /repos/:owner/:repo/git/blobs/:sha
rest.get(
'https://api.github.com/repos/:owner/:repo/git/blobs/:sha',
async (req, res, ctx) => {
const { owner, repo, sha: encodedSha } = req.params as {
owner: string;
repo: string;
sha: string;
};
if (!encodedSha) {
return res(ctx.status(400), ctx.json({ error: 'SHA is required' }));
}
const sha = decodeURIComponent(encodedSha).trim();
// 환경 변수 유효성 검사
if (`${owner}/${repo}` !== process.env.GITHUB_REPOSITORY) {
return res(
ctx.status(403),
ctx.json({ error: `Unmockable resource: ${owner}/${repo}` })
);
}
if (!sha.includes('/')) {
return res(ctx.status(404), ctx.json({ error: `No mockable data for SHA: ${sha}` }));
}
const fullPath = nodepath.resolve(process.cwd(), sha);
const content = await fs.readFile(fullPath, 'utf-8');
const encoding = 'base64';
return res(
ctx.status(200),
ctx.json({
[Redacted Person],
content: Buffer.from(content, 'utf-8').toString(encoding),
encoding,
})
);
}
),
];
변경된 점 요약
타입 강화
최신 MSW API는 TypeScript를 기본적으로 지원하므로, 요청 및 응답에 관련된 타입(RestHandler, ctx.json)을 더 명확히 정의했습니다.
환경 변수 검증
요청 URL의 owner, repo 및 경로를 process.env와 비교하여 유효성을 확인하는 로직을 유지했습니다. 잘못된 요청에 대한 처리는 더 명확한 상태 코드와 메시지를 반환하도록 수정했습니다.
Promise 및 파일 시스템 처리 정리 fs-extra와 Promise.all을 사용하여 비동기 파일 시스템 작업을 더 효율적으로 처리했습니다.
에러 응답 처리
잘못된 경로, SHA, 또는 환경 변수 불일치 등의 경우 적절한 HTTP 상태 코드(400, 403, 404)를 반환하도록 개선했습니다.
실행 방법
의존성 설치
bash
npm install msw fs-extra esbuild-register
환경 변수 설정.env 파일 또는 환경 변수로 GITHUB_REPOSITORY를 설정합니다:
code
GITHUB_REPOSITORY=your-owner/your-repo
서버 실행
bash
node index.js
API 모킹 테스트
브라우저나 Node.js에서 https://api.github.com/repos/:owner/:repo/contents/:path와 같은 엔드포인트를 호출하면 모킹된 응답을 받을 수 있습니다.
이제 최신 MSW 버전을 활용해 더욱 안정적이고 유지보수 가능한 모킹 환경을 구축할 수 있습니다! 🎉