博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
json-server的关系图谱详解(Relationships)
阅读量:2238 次
发布时间:2019-05-09

本文共 1617 字,大约阅读时间需要 5 分钟。

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数据内容解释一下:

这个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 } ]

转载于:https://www.cnblogs.com/vicky-li/p/json-server.html

你可能感兴趣的文章
GAN 的 keras 实现
查看>>
AI 在 marketing 上的应用
查看>>
Logistic regression 为什么用 sigmoid ?
查看>>
Logistic Regression 为什么用极大似然函数
查看>>
SVM 的核函数选择和调参
查看>>
LightGBM 如何调参
查看>>
用 TensorFlow.js 在浏览器中训练神经网络
查看>>
cs230 深度学习 Lecture 2 编程作业: Logistic Regression with a Neural Network mindset
查看>>
梯度消失问题与如何选择激活函数
查看>>
为什么需要 Mini-batch 梯度下降,及 TensorFlow 应用举例
查看>>
为什么在优化算法中使用指数加权平均
查看>>
初探Java设计模式4:一文带你掌握JDK中的设计模式
查看>>
初探Java设计模式5:一文了解Spring涉及到的9种设计模式
查看>>
Java集合详解1:一文读懂ArrayList,Vector与Stack使用方法和实现原理
查看>>
Java集合详解2:一文读懂Queue和LinkedList
查看>>
Java集合详解3:一文读懂Iterator,fail-fast机制与比较器
查看>>
Java集合详解4:一文读懂HashMap和HashTable的区别以及常见面试题
查看>>
Java集合详解5:深入理解LinkedHashMap和LRU缓存
查看>>
Java集合详解6:这次,从头到尾带你解读Java中的红黑树
查看>>
Java集合详解8:Java集合类细节精讲,细节决定成败
查看>>