【问题标题】:Json-Server DELETE without CASCADE?没有级联的Json-Server DELETE?
【发布时间】:2021-05-23 05:12:39
【问题描述】:

我在 Angular 项目中使用 json-server 模拟 REST API。适用于除 DELETE 之外的所有内容,其中包含多个 ID 列的任何和所有我的 json 对象都会在发出 DELETE 请求时被删除。

假设我有以下一组具有相关“accountId”ID 列的对象:

"accountfiles": [{
    id: 9001,
    accountId: 1001,
    filename: 'test.docx',
  },  {
    id: 9002,
    accountId: 1002,
    filename: 'test.txt',
  },  {
    id: 9003,
    accountId: 1001,
    filename: 'taxes.pdf',
  },  {
    id: 9004,
    accountId: 1003,
    filename: 'layout.ppt',
  },  {
    id: 9005,
    accountId: 1002,
    filename: 'Spreadsheet 5.xlsx',
  }
)];

这些可在以下位置获得: http://localhost:3000/accountfiles

然后我删除了这个单独的对象: http://localhost:3000/accountfiles/1001

删除整个集合以及包含多个 ID 列的所有其他集合。

此外,如果我有一个 Account 类:

"account": [
  {
    "id": 1001,
    "isInactive": false,
    "name": "HK Asset Group",
    "accountLogoUrl": "/assets/img/logos/logo2.png",
    "location": "Minneapolis MN 55434"
  }
]

并且我删除了账号id:1001,整​​个accountfiles集合也被删除了。

我尝试使用 --no-cascade-delete 启动标志无济于事(似乎不是当前 json-server 构建的一部分)。

难道不能在 json-server 中托管相关数据并进行有效删除吗?

谢谢

【问题讨论】:

  • 这里有同样的问题。你解决了吗?

标签: json-server


【解决方案1】:

迟到的答案,但迟到总比没有好。 这个问题仍然是相关的。 我设法通过将所有删除重定向到自定义中间件来绕过这种行为。 首先,处理复杂方面需要一个能够处理与您的逻辑相关的所有合规性的中间件。

const SERVER = JSON_SERVER.create();
.
.
.
SERVER.delete('/api/entities/:id', (req, res) => dbUtils.deleteEntities(req, res));

然后在您的 deleteEntities() 方法中获取对您的数据库的引用并相应地管理记录:

var ROUTER = JSON_SERVER.router('./db/db.json');
.
.
.
var paramID = req.params?.id;
var db = router.db;
var ents = db.get('entitieAs').valueOf(); // gets entitieAs collection

db.set('entitieAs', ents.filter(element=>element.id === paramID)).write(); // replace the target collection by the resulting collection after delete

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-11
    • 2012-11-06
    • 1970-01-01
    • 2012-07-17
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多