Loopback:检测模型的变化
Loopback: detect a change in the model
我在我的 /models/LocatableUser.js 中尝试使用的钩子的总体目标是弄清楚是否有我需要更新的实际更改,如果有,请做一些事情(打另一个 api 电话)。
我有一个继承自该自定义模型的自定义模型结构,因此在 parent 模型中定义 before save
挂钩时它适用于两个子模型。这是我在 parent 模型 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
的具体 class,调用 LocatableUser.findById()
将找不到任何内容,因为实际的 class 将是 LocatableUser
中的 child class。我发现唯一可行的是在 child class 中定义此方法,但会重复代码。
有没有办法从 LocatableUser
class 调用派生的 classes' findById
方法?
环回版本 2.22.0
原来我做错了:
在 PUT 调用中,ctx.currentInstance
作为当前存储的实例出现,我无需通过 ID 查询同一实例。 ctx.data
对象是来自对其余 API 的调用的实际有效负载,因此我可以将来自该对象的数据与 currentInstance
进行比较,以确定我是否需要运行 一些更新逻辑。
我在我的 /models/LocatableUser.js 中尝试使用的钩子的总体目标是弄清楚是否有我需要更新的实际更改,如果有,请做一些事情(打另一个 api 电话)。
我有一个继承自该自定义模型的自定义模型结构,因此在 parent 模型中定义 before save
挂钩时它适用于两个子模型。这是我在 parent 模型 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
的具体 class,调用 LocatableUser.findById()
将找不到任何内容,因为实际的 class 将是 LocatableUser
中的 child class。我发现唯一可行的是在 child class 中定义此方法,但会重复代码。
有没有办法从 LocatableUser
class 调用派生的 classes' findById
方法?
环回版本 2.22.0
原来我做错了:
在 PUT 调用中,ctx.currentInstance
作为当前存储的实例出现,我无需通过 ID 查询同一实例。 ctx.data
对象是来自对其余 API 的调用的实际有效负载,因此我可以将来自该对象的数据与 currentInstance
进行比较,以确定我是否需要运行 一些更新逻辑。