jsonserver

モックサーバー

6,7 月頃、jsonserver でテスト用のサーバを立てて開発をしていました。 ふと思い出したけど全然覚えてなかったのでおまとめ。

jsonserver

インストール

公式そのままに。

npm install -g json-server

データファイル

jsonserver は json ファイルに返却するデータを書きます。

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

こんなファイルだと、localhost/posts に GET を投げると posts の中に書いたデータが返ってきます。
また、id を書くと localhost/posts/1 で指定した id のデータのみが返ってきます。

起動

デフォルトだとポートは 3000 を使います。

json-server --watch db.json

ポートをかえる場合はこう

json-server --watch db.json --port 3004

GET してみる

curl http://localhost:3000/posts/
[
  {
    "id": 1,
    "title": "json-server",
    "author": "typicode"
  },
  {
    "id": 2,
    "title": "json-server2",
    "author": "typicode2"
  }
]

id 指定

curl http://localhost:3000/posts/2
{
  "id": 2,
  "title": "json-server2",
  "author": "typicode2"
}

GET 偽装

jsonserver に POST を投げると、データが更新されます。
前使っていた時はこれだと非常に都合が悪かったので、middlewares ファイルを作成して POST を投げたときは GET に偽装していました。

module.exports = (req, res, next) => {
  if (req.method === "POST") {
    req.method = "GET";
    req.url += req.body.id ? req.body.id : "";
  }
  next();
};

POST のパラメータに id を含めていたので、url に id を追加しています。

実行するときはこう。

json-server --watch db.json --middlewares ./middle.js

パラメータ無しで post

curl -X POST http://localhost:3000/posts/
[
  {
    "id": 1,
    "title": "json-server",
    "author": "typicode"
  },
  {
    "id": 2,
    "title": "json-server2",
    "author": "typicode2"
  }
]

パラメータ付き

curl -X POST -d "id=2" http://localhost:3000/posts/
{
  "id": 2,
  "title": "json-server2",
  "author": "typicode2"
}