여러개의 Router를 생성하게 될텐데, 이렇게 되면 유지보수가 이후에는 어려워질수 있으니 router 모듈화를 진행
src/api/index.js
에 api에 관련된 호출을 나열
src/index.js
const Koa = require('koa');
const Router = require('koa-router');
const api = require('./api');
const app = new Koa();
const router = new Router();
// 라우터 설정
router.use('/api', api.routes()); // add api router
// app instance에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());
app.listen(4000, () => {
console.log('Listening to port 4000');
});
src/api/index.js
const Router = require('koa-router');
const api = new Router();
api.get('/test', ctx => {
ctx.body = 'test 성공';
});
module.exports = api;
src/api/index.js
를 생성하고, src/index.js
에 router.use
를 통해 router를 등록해주면 된다.
이때 주의해야할점은 src/api/index.js
에서 반드시 exports
를 해줘야 한다.
posts API 생성하기
src/api/posts/index.js
에 아래와 같이 posts
에 관련된 api의 목록들을 정의한다.
정의한 route를 src/api/index.js
에 적용을 해주면 된다.
src/api/index.js
const Router = require('koa-router');
const posts = require('./posts');
const api = new Router();
api.use('/posts', posts.routes());
module.exports = api;
src/api/posts/index.js
const Router = require('koa-router');
const posts = new Router();
const printInfo = ctx => {
ctx.body = {
method: ctx.method,
path: ctx.path,
params: ctx.params,
};
};
posts.get('/', printInfo);
posts.post('/', printInfo);
posts.get('/:id', printInfo);
posts.delete('/:id', printInfo);
posts.put('/:id', printInfo);
posts.patch('/:id', printInfo);
module.exports = posts;
위 같이 정의하고 http://localhost:4000/api/posts/12
을 호출하면 아래와 같은 결과가 나온다.