MSW란 Mock Service Worker로, 백엔드를 모킹하는 방법 중 하나이다.
백엔드 개발자가 아직 API를 완성하지 못하였을 때 완성 될 때까지 임시로 사용하기 위한 가짜 API를 만들어 놓는 것이다.
백엔드 개발자가 만들어야 하는 API를 우리가 만드는 셈 !
npm install msw --save-dev
src 밑에 mocks 폴더 만들고
browser.ts, http.ts를 만들어준다.
next.js에서는 msw가 서버에서도 돌고, 브라우저 클라이언트 환경에서도 돌아야 하는데, 아직 그게 매끄럽게 돌아가는 게 없어서 임시 노드 서버를 활용을 해서 돌린다!
/mocks/browser.ts
import { setupWorker } from 'msw/browser';
import { handlers } from './handlers';
// This configures a Service Worker with the given request handlers.
const worker = setupWorker(...handlers);
export default worker;
설치
npm i -D @mswjs/http-middleware express cors
npm i --save-dev @types/express @types/cors
/mocks/http.ts
import { createMiddleware } from '@mswjs/http-middleware';
import express from 'express';
import cors from 'cors';
import { handlers } from './handlers';
const app = express();
// 서버 포트번호 적기
const port = 9090;
// 프론트 주소 적기
app.use(cors({ origin: 'http://localhost:3000', optionsSuccessStatus: 200, credentials: true }));
app.use(express.json());
app.use(createMiddleware(...handlers));
app.listen(port, () => console.log(`Mock server is running on port: ${port}`));
/mocks/handlers.ts
사용할 api 넣어주면 됨!
import { http, HttpResponse } from 'msw';
const User = [
{ id: 'elonmusk', nickname: 'Elon Musk', image: '/yRsRRjGO.jpg' },
{ id: 'zerohch0', nickname: '제로초', image: '/5Udwvqim.jpg' },
{ id: 'leoturtle', nickname: '레오', image: '/yRsRRjGO.jpg' },
];
export const handlers = [
http.post('/api/login', () => {
console.log('로그인');
return HttpResponse.json(User[1], {
headers: {
'Set-Cookie': 'connect.sid=msw-cookie;HttpOnly;Path=/',
},
});
}),
http.post('/api/logout', () => {
console.log('로그아웃');
return new HttpResponse(null, {
headers: {
'Set-Cookie': 'connect.sid=;HttpOnly;Path=/;Max-Age=0',
},
});
}),
http.post('/api/users', async ({ request }) => {
console.log('회원가입');
return HttpResponse.text(JSON.stringify('ok'), {
headers: {
'Set-Cookie': 'connect.sid=msw-cookie;HttpOnly;Path=/;Max-Age=0',
},
});
}),
http.get('/api/followRecommends', ({ request }) => {
return HttpResponse.json(User);
}),
http.get('/api/trends', ({ request }) => {
return HttpResponse.json([
{ tagId: 1, title: '제로초', count: 1264 },
{ tagId: 2, title: '원초', count: 1264 },
{ tagId: 3, title: '투초', count: 1264 },
{ tagId: 4, title: '쓰리초', count: 1264 },
{ tagId: 5, title: '포초', count: 1264 },
{ tagId: 6, title: '파이브초', count: 1264 },
{ tagId: 7, title: '식스초', count: 1264 },
{ tagId: 8, title: '세븐초', count: 1264 },
{ tagId: 9, title: '나인초', count: 1264 },
]);
}),
];
이 아니라
package.json
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"export": "next export",
"lint": "next lint",
"mock": "npx tsx watch ./src/mocks/http.ts"
},
이렇게 정의 해주고
npm run mock 으로 mock 서버까지 띄우면 진짜 끝 !