[JavaScript] JSON Server로 Mock API 만들기

olwooz·2023년 1월 30일
1

JavaScript

목록 보기
5/5

JSON Server

JavaScript 환경에서 가상의 REST API 서버를 쉽게 만들 수 있게 해주는 라이브러리다.
진행했던 프로젝트의 서버를 닫게 돼서, 데모 버전을 만들기 위해 사용하게 됐다.

GitHub: https://github.com/typicode/json-server
npm: https://www.npmjs.com/package/json-server

세팅

1. 설치

npm i -g json-server

2. 데이터 생성

db.json이라는 파일을 만들어서 원하는 JSON 데이터를 집어넣는다.
관리하기 편하게 mock-server등 디렉토리를 만들어 그 안에 db.json 파일을 넣는 것이 좋아 보인다.

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "olwooz" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "olwooz" }
}

3. 서버 구동

json-server --watch db.json --port 3001

--port 옵션을 넣지 않으면 기본적으로 3000번 포트에서 구동되는데, 이는 리액트 개발 서버 기본 포트와 겹치기 때문에 3001번 포트라고 명시해줬다.

사용

서버를 구동하고 localhost:3001/comments에 접속한 결과다.
이제 localhost:3001/${route}GET, POST, PUT, PATCH, DELETE 요청을 보낼 수 있다.

Routes

기본으로 제공되는 Routes는 다음과 같다.

1. Plural Routes

GET    /posts
GET    /posts/1
POST   /posts
PUT    /posts/1
PATCH  /posts/1
DELETE /posts/1

2. Singular Routes

GET    /profile
POST   /profile
PUT    /profile
PATCH  /profile

3. Filter

GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode

.을 사용하면 하위 속성에 접근할 수 있다.

4. Paginate

_page_limit (default=10)을 사용해 페이지네이션을 할 수 있다.
Link 응답 헤더에 first, prev, next, last 링크가 주어진다.

GET /posts?_page=7
GET /posts?_page=7&_limit=20

5. Sort

_sort_order (default=asc)를 사용해 정렬할 수 있다.

GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc

그 외에도 Slice, Operator, Full-text Search 등을 지원한다.

Custom Routes

routes.json 파일에 아래와 같이 사용자 지정 routes를 정의할 수 있다.

{
  "/api/*": "/$1",
  "/:resource/:id/show": "/:resource/:id",
  "/posts/:category": "/posts?category=:category",
  "/articles\\?id=:id": "/posts/:id"
}

Middlewares

CLI에서 --middlewares 옵션으로 미들웨어를 추가할 수 있다.

// hello.js
module.exports = (req, res, next) => {
  res.header('X-Hello', 'World')
  next()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js

1개의 댓글

comment-user-thumbnail
2023년 5월 6일

감사합니다! 덕분에 json-server에 대해 학습하고 가요!

답글 달기