如何从单个 object 而不是 json-server 中的数组检索 children?
How to retrive children from a single object intead of array in json-server?
我正在使用 json-server for mock-backend 从单个 object 中检索 children。
parent table sentinel
和 child table sensor
如您所见,sensors
是一个数组,sentinel
是一个 object。
我已经使用 http://localhost:3000/sentinel?_embed=sensors
但响应不是我所期望的,因为我想要 sensors: [{id: 1}, {id: 2}, ecc]
official documentation 表明有两种方法可以检索两个 table:
_embed(包括 children)和 _expand(包括 parent)。
我怎样才能达到这个结果?
鉴于 sentinel
是您 db.json
中的单个对象,并且您不能拥有多个 sentinel
我不清楚您的查询与检索有何不同所有带有 sentinelId=10
的传感器:
/sensors?sentinelId=10
事实上,如果你尝试这个 API:
/sentinel/10/sensors
它会起作用,因为 json-服务器将 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
我正在使用 json-server for mock-backend 从单个 object 中检索 children。
parent table sentinel
和 child table sensor
如您所见,sensors
是一个数组,sentinel
是一个 object。
我已经使用 http://localhost:3000/sentinel?_embed=sensors
但响应不是我所期望的,因为我想要 sensors: [{id: 1}, {id: 2}, ecc]
official documentation 表明有两种方法可以检索两个 table:
_embed(包括 children)和 _expand(包括 parent)。
我怎样才能达到这个结果?
鉴于 sentinel
是您 db.json
中的单个对象,并且您不能拥有多个 sentinel
我不清楚您的查询与检索有何不同所有带有 sentinelId=10
的传感器:
/sensors?sentinelId=10
事实上,如果你尝试这个 API:
/sentinel/10/sensors
它会起作用,因为 json-服务器将 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