node.jsのjson-serverを利用する
json-serverというライブラリが素敵な感じ。
導入
ローカルに導入するとして。。。
1. 展開場所確保
npm init
2. インストール
npm install json-server
3. キック用にpackage.jason書き換え
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"json-server": "json-server"
},
4.mockデータファイル用意。例えばこんな感じのjsonだとするとtop下の階層がエンドポイントになる感じ。
mockdata.json
{
"movies": [
{ "title": "マトリックス", "rating": 9.1},
{ "title": "タイタニック", "rating": 8.8}
],
"user": [
{"name": "fukuhara", "age": 35, "sex": "male"},
{"name": "sugiyama", "age": 42, "sex": "male"}
]
}
5.mockサーバ起動
npm run json-server -- --watch mockdata.json
npm WARN lifecycle The node binary used for scripts is C:\Program Files (x86)\Nodist\bin\node.exe but npm is using C:\Program Files (x86)\Nodist\v-x64\10.15.3\node.exe itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.
> restmock@1.0.0 json-server H:\work\restmock
> json-server "--watch" "mockdata.json"
\{^_^}/ hi!
Loading mockdata.json
Done
Resources
http://localhost:3000/movies
http://localhost:3000/user
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
6.Curlでちょっと叩いてみる
curl -X GET "http://localhost:3000/movies"
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 126 100 126 0 0 126 0 0:00:01 --:--:-- 0:00:01 473[
{
"title": "マトリックス",
"rating": 9.1
},
{
"title": "タイタニック",
"rating": 8.8
}
]
できること
登録/更新/削除操作ができる
登録
curl -X POST -H "Content-Type: application/json" -d '{
"title": "test1",
"id":1
}' "http://localhost:3000/movies"
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 65 100 33 100 32 33 32 0:00:01 --:--:-- 0:00:01 277{
"title": "test1",
"id": 1
}
curl -X GET "http://localhost:3000/movies/"
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 169 100 169 0 0 169 0 0:00:01 --:--:-- 0:00:01 722[
{
"title": "マトリックス",
"rating": 9.1
},
{
"title": "タイタニック",
"rating": 8.8
},
{
"title": "test1",
"id": 1
}
]
curl -X GET "http://localhost:3000/movies/1"
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 33 100 33 0 0 33 0 0:00:01 --:--:-- 0:00:01 150{
"title": "test1",
"id": 1
}
- 更新系作業時は「id」ってフィールド無いとダメっぽい。
- 逆に「id」フィールドさえあれば他はチェックしてないくさい
更新されたmockデータのjsonをスナップショットとして保存できる
ctrl+s
Saved snapshot to db-1582737815807.json