问题描述
我使用 json-server 作为模拟后端来检索单个对象的子对象。
父表 sentinel
和子表 sensor
如您所见,sensors
是一个数组,而 sentinel
是一个对象。
我使用了 http://localhost:3000/sentinel?_embed=sensors
但响应不是我所期望的,因为我想要 sensors: [{id: 1},{id: 2},ecc]
official documentation 显示了检索两个表的两种方法:
_embed(包括子项)和 _expand(包括父项)。
我怎样才能达到这个结果?
解决方法
鉴于 sentinel
是 db.json
中的单个对象,并且您不能拥有多个 sentinel
,我不清楚您的查询与检索所有传感器有何不同sentinelId=10
:
/sensors?sentinelId=10
事实上,如果你尝试这个 API:
/sentinel/10/sensors
它会起作用,因为 json-server 将 url 完全重写为上一个查询。
如果由于某种原因您不想直接在查询中使用 sentinel
id,另一种选择是使用 json-server 作为模块并使用您需要的逻辑定义自定义路由。下面是一个基本示例,它公开 /sentinel/sensors
API 并检索 sentinel
数据以及 sentinelId
等于当前 sentinel
id 的传感器:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;
server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors',(req,res) => {
const sentinel = db.get('sentinel').value();
const sensors = db
.get('sensors')
.filter({ sentinelId: sentinel.id })
.value();
res.send({ ...sentinel,sensors: sensors });
});
server.use(router);
server.listen(3001,() => {
console.log('Mock server is running on port ' + 3001);
});
那会给你这样的回应:
{
"id": 10,"name": "Sentinel","sensors": [
{
"id": 1,"sentinelId": 10
},{
"id": 2,"sentinelId": 10
}
]
}
这是一个stackblitz