【问题标题】:How to retrive children from a single object intead of array in json-server?如何从单个对象而不是 json-server 中的数组中检索子对象?
【发布时间】:2021-10-04 06:40:54
【问题描述】:

我正在使用 json-server 进行模拟后端以从单个对象中检索子对象。
父表sentinel和子表sensor

如您所见,sensors 是一个数组,sentinel 是一个对象。
我使用了http://localhost:3000/sentinel?_embed=sensors,但响应不是我所期望的,因为我想要sensors: [{id: 1}, {id: 2}, ecc]

official documentation 显示了检索两个表的两种方法:
_embed(包括子项)和 _expand(包括父项)。

我怎样才能达到这个结果?

【问题讨论】:

  • 如果表是单个对象,sentinel 如何表示表?您的数据库中可以有多个sentinel 吗? (Please do note upload images of code on SO)
  • @Ibsn 感谢您的回答,我不会再发布图片了。我是编程语言世界的新手,所以如果我的话不是“技术性的”,我很抱歉。假设db.json 是表sentinel 中的一个MySQL 数据库,我将只有一条记录,并且通过一个GET 请求,我想检索sentinel 信息以及所有sensors

标签: json typescript backend json-server


【解决方案1】:

鉴于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

【讨论】:

  • 感谢您的回答,您的 API 都只检索 sensors 信息,但我需要将 sensors 嵌套到对象 sentinel 中,使用路由参数而不定义自定义路由(如果可能的话)跨度>
  • 这是不可能的,除非在您的 db.json 中您将 sentinel 定义为包含单个项目的列表。在这种情况下,_embed 会起作用。我更新了答案,让自定义路由返回您期望的响应。
  • 感谢示例和解释,它成功了!!
  • 很高兴为您提供帮助。请考虑接受答案。
猜你喜欢
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 2018-03-06
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
相关资源
最近更新 更多