json-server
的关系图谱
json-server
是非常好用的一款模拟REST API的工具,文档也很详细和全面.
示例数据
官网上对于关系图谱的案例非常好,我这里在它示例的基础上稍以改进,进行说明,首先我这里编写了一个原始数据,db.json
:
{ "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
数据内容解释一下:
posts
跟comments
是有关联的,他们的关系通过的就是comments
下postId
属性,postId
对应的就是posts
的id
。比如comments
下postId:2
的对象关联的就是posts下的{ "id": 2, "title": "post的第二个title", "author": "tangcaiye" }
_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
数据:返回结果: [ { "id": 1, "body": "some comment1111", "postId": 2 } ]