JavaScript 환경에서 가상의 REST API 서버를 쉽게 만들 수 있게 해주는 라이브러리다.
진행했던 프로젝트의 서버를 닫게 돼서, 데모 버전을 만들기 위해 사용하게 됐다.
GitHub: https://github.com/typicode/json-server
npm: https://www.npmjs.com/package/json-server
npm i -g json-server
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" }
}
json-server --watch db.json --port 3001
--port
옵션을 넣지 않으면 기본적으로 3000번 포트에서 구동되는데, 이는 리액트 개발 서버 기본 포트와 겹치기 때문에 3001번 포트라고 명시해줬다.
서버를 구동하고 localhost:3001/comments
에 접속한 결과다.
이제 localhost:3001/${route}
로 GET
, POST
, PUT
, PATCH
, DELETE
요청을 보낼 수 있다.
기본으로 제공되는 Routes는 다음과 같다.
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
GET /profile
POST /profile
PUT /profile
PATCH /profile
GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode
.
을 사용하면 하위 속성에 접근할 수 있다.
_page
와 _limit (default=10)
을 사용해 페이지네이션을 할 수 있다.
Link
응답 헤더에 first
, prev
, next
, last
링크가 주어진다.
GET /posts?_page=7
GET /posts?_page=7&_limit=20
_sort
와 _order (default=asc)
를 사용해 정렬할 수 있다.
GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc
그 외에도 Slice, Operator, Full-text Search 등을 지원한다.
routes.json
파일에 아래와 같이 사용자 지정 routes를 정의할 수 있다.
{
"/api/*": "/$1",
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles\\?id=:id": "/posts/:id"
}
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
감사합니다! 덕분에 json-server에 대해 학습하고 가요!