首页 > 解决方案 > 在生命周期回调中触发另一个 API 调用 - Strapi

问题描述

我有两种内容类型:产品和 TempBaskets

Products 包含一个字段;stock-total我想根据使用此形状创建或更新的 TempBaskets 进行更改:

{ 
 "products":{
   "test-product": {
     "quantity":1,
     "id":"5b945b5b91f2d31698893914",
     "price":123
   }
 },
 "id":"5bb6a2c34f119f72182ec975",
 "totals": {
   "items":1,
   "price":123
 }
}

我想在 TempBaskets 生命周期挂钩中捕获这些数据,然后调用 Products 控制器之一并将测试产品的库存更新为 -1。

afterUpdate: async (model, result) => {
    console.log(model);
    console.log(result);
    console.log(model.products); // undefined
    console.log(model.body); // undefined
    console.log(model.data); // clutching at straws - undefined 
}

model并且result是猫鼬对象。文档似乎建议model.products应该包含我需要的数据 - 但它是未定义的。

如何从生命周期方法中的调用访问数据?

然后我可以在生命周期挂钩中使用 Products 中的控制器吗?

最后,(对不起堆栈溢出神)这是正确的方法吗?

谢谢!

标签: mongoosestrapi

解决方案


我刚刚遇到了这个问题,我不确定这是否是完美的方法,但这就是我解决它的方法。

// Before updating a value.
// Fired before an `update` query.
beforeUpdate: async function(model) {
  // Get _id of project being updated
  let documentId = model._conditions._id;
  // Tack it on to the middleware chain so it can be used in post save hook
  this.documentId = documentId;
},

// After updating a value.
// Fired after an `update` query.
afterUpdate: async function(model, result) {
  // Pull the updated project
  let updatedDocument = await this.findById(this.documentId);
},

注意更改async (model) => {}async function(model){}。Mongoose 中间件以链的形式运行,因此您可以将数据从 pre-hook 传递到 post-hook。这感觉就像是在进行额外的数据库调用,但由于 Mongoose 的工作方式,我不确定是否有任何方法可以解决这个问题。


推荐阅读