코딩/Node.js
[koa] koa 학습하기 - 2 - 컨트롤러 적용
카슈밀
2024. 12. 8. 03:13
반응형
yarn add koa-bodyparser
// index.js
// 내용 수정한다
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodpareser');
const api = require('./api');
const app = new Koa();
const router = new Router();
router.use('/api', api.routes());
// 라우터 적용전에 적용
app.use(bodyParser());
// app 인스턴스에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());
app.listen(4000, () => {
console.log('Listening to port 4000');
});
컨트롤러를 적용한 부분이다.
// api/posts/index.js
const Router = require('koa-router');
const postCtrl = require('./posts.ctrl');
const posts = new Router();
posts.get('/', postCtrl.list);
posts.post('/', postCtrl.write);
posts.get('/:id', postCtrl.read);
posts.delete('/:id', postCtrl.delete);
posts.put('/:id', postCtrl.replace);
posts.patch('/:id', postCtrl.update);
module.exports = posts;
해당 부분은 컨트롤러로 매칭시킬 수 있게 객체 형태로 export 하는 부분.
// /api/posts/post.ctrl.js
let postId = 1;
const posts = [
{
id: 1,
title: '제목',
body: '내용',
},
];
/* 포스트 작성
POST /api/posts
{ title, body }
*/
exports.write = (ctx) => {
const { title, body } = ctx.request.body;
postId += 1;
const post = { id: postId, title, body };
posts.push(post);
ctx.body = post;
};
/* 포스트 목록 조회
GET /api/posts
*/
exports.list = (ctx) => {
ctx.body = posts;
};
/* 특정 포스트 조회
GET /api/posts/:id
{ title, body }
*/
exports.read = (ctx) => {
const { id } = ctx.params;
const post = posts.find((p) => p.id.toString() === id);
if (!post) {
ctx.status = 404;
ctx.body = {
message: '포스트가 존재하지 않습니다',
};
return;
}
ctx.body = post;
};
/* 포스트 제거
DELETE /api/posts/:id
*/
exports.remove = (ctx) => {
const { id } = ctx.params;
const index = posts.findIndex((p) => p.id.toString() === id);
if (index === -1) {
ctx.status = 404;
ctx.body = {
message: '포스트가 존재하지 않습니다',
};
return;
}
posts.splice(index, 1);
ctx.status = 204;
};
/* 포스트 수정(교체)
PUT /api/posts/:id
{ title, body }
*/
exports.replace = (ctx) => {
const { id } = ctx.params;
const index = posts.find((p) => p.id.toString() === id);
if (index === -1) {
ctx.status = 404;
ctx.body = {
message: '포스트가 존재하지 않습니다',
};
return;
}
posts[index] = {
id,
...ctx.request.body,
};
ctx.body = posts[index];
};
/* 포스트 수정(특정 필드 변경)
PATCH /api/posts/:id
{ title, body }
*/
exports.update = (ctx) => {
const { id } = ctx.params;
const index = posts.find((p) => p.id.toString() === id);
if (index === -1) {
ctx.status = 404;
ctx.body = {
message: '포스트가 존재하지 않습니다',
};
return;
}
posts[index] = {
...posts[index],
...ctx.request.body,
};
ctx.body = posts[index];
};
728x90