TIL | #23 Node.js | Koa 프레임워크, postman

trevor1107·2021년 4월 15일
0

2021-04-13(화)

Koa 프레임워크

폴더 생성

yarn init -y

yarn add koa koa-router koa-bodyparser

// package.json
"scripts": {
    "start": "node src",
    "start:dev": "nodemon --watch src/ src/index.js"
}

--watch src/ : src폴더에 변경되는 부분이 있다면 src/index.js를 다시 실행하라는 구문이다.

// api/index.js
const Router = require('koa-router');
const api = new Router();
const posts = require('./posts');

api.use('/posts', posts.routes());

module.exports = api;
// index.js
const koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const api = require('./api');
const app = new koa();
const router = new Router();

// ctx (context의 약어)
// 웹 요청과 응답에 관한 정보이다.
// next
// 현재 처리중인 미들웨어의 다음 미들웨어를 호출하는 함수이다.
// 미들웨어를 등록하고 next를 호출하지 않으면 그 다음 미들웨어를 실행하지 않는다.
// 만약 미들웨어에서 next를 사용하지 않으면 ctx=>{}와 같은 형태로 매개변수에 next를 설정하지 않아도 된다.

// 라우터 적용 전에 bodyparser 적용
app.use(bodyParser());

router.use('/api', api.routes());

// app instance에 라우터를 적용한다.
app.use(router.routes()).use(router.allowedMethods());
app.listen(4000, () => {
    console.log('4000번 포트에서 대기중');
});

Postman

포스트맨은 API 테스트 도구이며, 서버에 요청 및 응답을 확인할 수 있다.
포스트맨 사용법은 여기를 참고하기를..

포스트맨을 이용해서 REST API 요청 및 응답에 대해서 작성해보자.

// api/posts/posts.ctrl.js
let postId = 1;

const posts = [
    {
        id: 1,
        title: '제목',
        body: '내용',
    },
];

// 포스트 작성
// POST /api/posts
// {title, body}

exports.write = (ctx) => {
    //REST API의 request body는 ctx.request.body를 조회할 수 있다.
    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
exports.read = (ctx) => {
    const { id } = ctx.params;
    // 파라미터로 받아온 값은 문자열 형식으로 파라미터를 숫자로
    // 변환하거나, 비교할 p.id값을 문자열로 변경해야 한다.
    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;

    // 해당 id를 가진 포스트가 몇번째 인덱스인지 확인
    const index = posts.findIndex((p) => p.id.toString() === id);

    if (index === -1) {
        ctx.status = 404;
        ctx.body = {
            message: '존재하지 않는다.',
        };
        return;
    }

    // idx번째 제거
    posts.splice(index, 1);
    ctx.status = 204;
};

// 포스트 수정(교체)
// PUT /api/posts/:id
// { title, body }
// 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;
    }

    // 전체 객체를 덮어 씌운다. 따라서 id를 제외한 기본 정보를
    // 버리고, 객체를 새로 만든다.
    posts[index] = {
        id,
        ...ctx.request.body,
    };

    ctx.body = posts[index];
};

// 특정 포스트 수정(특정 필드 변경)
// PATCH /api/posts/:id
// { title, body }
// 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];
};
// api/posts/index.js
const Router = require('koa-router');
const postsCtrl = require('./posts.ctrl');
const posts = new Router();

posts.get('/', postsCtrl.list);
posts.post('/', postsCtrl.write);
posts.get('/:id', postsCtrl.read);
posts.delete('/:id', postsCtrl.remove);
posts.put('/:id', postsCtrl.replace);
posts.patch('/:id', postsCtrl.update);

module.exports = posts;
profile
프론트엔드 개발자

0개의 댓글