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文件中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
}
]
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 感觉程序员要被 AI 淘汰了?学什么才有机会?
· BotSharp + MCP 三步实现智能体开发
· AI团队比单打独斗强!CrewAI多智能体协作系统开发踩坑全解析
· 3. RabbitMQ 的(Hello World) 和 RabbitMQ 的(Work Queue
· 动物智能之数据标注员——狗篇