json-server
的关系图谱json-server
是很是好用的一款模拟REST API的工具,文档也很详细和全面.
详情:json-server
而其中的关系图谱是它很是强大的一个功能,能够很是方便实现多个路由之间关联数据的获取。git
官网上对于关系图谱的案例很是好,我这里在它示例的基础上稍以改进,进行说明,首先我这里编写了一个原始数据,db.json
:github
{ "posts": [ { "id": 1, "title": "post的第一个title", "author": "typicode" }, { "id": 2, "title": "post的第二个title", "author": "tangcaiye" } ], "comments": [ { "id": 1, "body": "some comment1111", "postId": 2 }, { "id": 2, "body": "some comment2222", "postId": 1 } ], "profile": { "name": "typicode" } }
这里对这个db.json
数据内容解释一下:
这个json文件中posts
跟comments
是有关联的,他们的关系经过的就是comments
下postId
属性,postId
对应的就是posts
的id
。
好比comments
下postId:2
的对象关联的就是posts下的{ "id": 2, "title": "post的第二个title", "author": "tangcaiye" }
json
_embed
json-server
中的_embed
就是用来获取包含下级资源的数据.
好比我json-server
服务器的端口号是8081
,而后个人请求路径是http://localhost:8081/posts/2?_embed=comments
这个路径获取的就是posts下的id为2的数据和它关联的comments的数据:{ "id": 1, "body": "some comment1111", "postId": 2 }
输出结果为:服务器
{ "id": 2, "title": "post的第二个title", "author": "tangcaiye", "comments": [ { "id": 1, "body": "some comment1111", "postId": 2 } ] }
_expand
若是理解了_embed
那么_expand
它也就很轻松了,_expand
获取的是包含上级资源的数据:
路径:http://localhost:8081/comments/2?_expand=post
上面这个路径获取的就是comments
下id
为2的数据和它关联的上级资源post
,也就是posts
下的:{ "id": 1, "title": "post的第一个title", "author": "typicode" }
输出结果:工具
{ "id": 2, "body": "some comment2222", "postId": 1, "post": { "id": 1, "title": "post的第一个title", "author": "typicode" } }
有时候咱们可能想只获取下级资源,能够经过:
路径:http://localhost:8081/posts/2/comments
上面这个路径就是获取posts
的id:2
所关联的comments
数据:
返回结果:post
[ { "id": 1, "body": "some comment1111", "postId": 2 } ]