Loopback:检测模型中的变化
问题描述:
我在钩子中的总体目标我试图在我的/models/LocatableUser.js中使用这里是找出是否有我需要更新的实际更改,如果有是,做点什么(做另一个API调用)。Loopback:检测模型中的变化
我有一个继承自此自定义模型的自定义模型的结构,因此它在父模型中定义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
的一些小孩班。我发现唯一可行的是在两个子类中定义这个方法,但是它重复了代码。
有没有办法让派生类的findById
方法调用LocatableUser
类?
回环版本2.22.0
答
因此,原来我要对这个错误的方法:
在PUT调用,ctx.currentInstance
进来作为当前存储的情况下,不再需要我来通过ID查询同一个实例。 ctx.data
对象是来自调用其余API的实际有效内容,因此我可以将从中进入的数据与currentInstance
进行比较,以确定是否需要运行某些更新逻辑。
如果你看看ctx,你能找出正在使用的实际班级吗? –
经过仔细检查,它看起来好像在ctx.Model.definition中有一个类名称字段......但这可能是比我想要做的更好的方法 – BrDaHa