json-server的关系图谱详解(Relationships)

json-server的关系图谱

json-server是非常好用的一款模拟REST API的工具,文档也很详细和全面.
详情:json-server
而其中的关系图谱是它非常强大的一个功能,可以非常方便实现多个路由之间关联数据的获取。

示例数据

官网上对于关系图谱的案例非常好,我这里在它示例的基础上稍以改进,进行说明,首先我这里编写了一个原始数据,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数据内容解释一下:
这个json文件中postscomments是有关联的,他们的关系通过的就是commentspostId属性,postId对应的就是postsid
比如commentspostId: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
上面这个路径获取的就是commentsid为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
上面这个路径就是获取postsid:2所关联的comments数据:
返回结果:

 
[
  {
    "id": 1,
    "body": "some comment1111",
    "postId": 2
  }
]