HTTP 프로토콜 장점을 살릴 수 있는 네트워크 기반 아키텍처로,
REST 기반으로 서비스 API를 구현한 것이다.
메서드 | 설명 |
---|---|
GET | 데이터를 조회할 때 사용 |
POST | 데이터를 등록할 때 사용 |
DELETE | 데이터를 지울 때 사용 |
PUT | 데이터를 새 정보로 통째로 교체할 때 사용 |
PATCH | 데이터의 특정 필드를 수정할 때 사용 |
종류 | 기능 |
---|---|
POST /posts | 포스트 작성 |
GET /posts | 포스트 목록 조회 |
GET /posts/:id | 특정 포스트 조회 |
DELETE /posts/:id | 특정 포스트 삭제 |
PATCH /posts/:id | 특정 포스트 업데이트 |
POST /posts/:id/comments | 특정 포스트에 덧글 등록 |
GET /posts/:id/comments | 특정 포스트의 덧글 목록 조회 |
DELETE /posts/:id/comments/:commentId | 특정 포스트의 특정 덧글 삭제 |
다음은 posts.ctrl.js 파일이다.
let postId = 1;
const posts = [
{
id: 1,
title: '제목',
body: '내용',
},
];
// POST 포스트 작성
exports.write = ctx => {
const { title, body } = ctx.request.body;
postId += 1;
const post = { id: postId, title, body };
posts.push(post);
ctx.body = post;
};
// GET 포스트 조회
exports.list = ctx => {
ctx.body = posts;
};
// GET 특정 포스트 조회
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 특정 포스트 제거
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 포스트 수정(교체)
// 전체 포스트 정보를 입력하여 데이터를 통째로 교체할 떄 사용
exports.replace = 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[index] = {
id,
...ctx.request.body,
};
ctx.body = posts[index];
};
// PATCH 포스트 수정(특정 필드 변경)
exports.update = 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[index] = {
...posts[index],
...ctx.request.body,
};
ctx.body = posts[index];
}
참고(리액트를 다루는 기술)