【问题标题】:Loopback: detect a change in the modelLoopback:检测模型的变化
【发布时间】:2016-05-19 01:48:39
【问题描述】:

我在 /models/LocatableUser.js 中尝试使用的钩子中的总体目标是确定是否有需要更新的实际更改,如果有,请执行某些操作(制作另一个 api称呼)。

我有一个继承自该自定义模型的自定义模型结构,因此在父模型中定义 before save 挂钩时,它适用于两个子模型。这是我在父模型LocatableUser中定义的方法的示例:

LocatableUser.observe('before save', function (ctx, next) {
    if (ctx.instance){  // new record
      ctx.instance._address.getGeopoint(function (error, location) {
        setLocation(error, location, ctx.instance, next);
      });
    } else if (ctx.currentInstance) { // this is an update, currentInstance is treated as immutable
      LocatableUser.findById(ctx.currentInstance.id, function(err, data) {
        console.log('Locatable User: current data is: ', err, data)
      })
      console.log('Locatable User: ctx is:', ctx);
      ctx.currentInstance._address.getGeopoint(function (error, location) {
        setLocation(error, location, ctx.data, next);
      });
    } else {
      console.warn('no context instance');
    }
  });

这段代码的问题是,由于没有LocatableUser 的具体类,调用LocatableUser.findById() 不会找到任何东西,因为实际的类将是LocatableUser 的某个子类。我发现唯一可行的方法是在两个子类中定义此方法,但这会重复代码。

有没有办法从LocatableUser 类调用派生类的findById 方法?

环回版本 2.22.0

【问题讨论】:

  • 如果你看一下 ctx,你能弄清楚实际使用的类吗?
  • 仔细观察,在 ctx.Model.definition 中确实有一个类名字段...但这可能是比我尝试做的更好的方法

标签: loopbackjs


【解决方案1】:

所以事实证明我做错了:

在 PUT 调用中,ctx.currentInstance 作为当前存储的实例出现,我无需通过 ID 查询相同的实例。 ctx.data 对象是来自调用其余 API 的实际负载,因此我可以将来自该 API 的数据与 currentInstance 进行比较,以确定是否需要运行一些更新逻辑。

【讨论】:

    猜你喜欢
    • 2016-09-29
    • 2020-07-27
    • 2013-03-03
    • 1970-01-01
    • 2013-05-17
    • 2017-12-08
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    相关资源
    最近更新 更多