我说的是loopback push组件。我试图拦截"创建" "安装方法"模型。我的代码看起来像这样 -
服务器/引导/ installationex.js
module.exports = function (app) {
var Installation = app.models.Installation;
var create = Installation.create;
Installation.create = function (data, cb) {
//reinitializing old implementation
this.create = create;
console.log("Received data: "+JSON.stringify(data));
if (!data || !data.imei) {
console.log("No data or imei was provided, creating new");
this.create(data, cb);
return;
}
//saving 'this' reference
var that = this;
//search by imei filter
var filter = {where: {imei: data.imei}};
this.findOne(filter, function (err, result) {
if (err) {
console.log("Error occurred while looking for installation by IMEI");
cb(err);
return;
}
if (!result) {
console.log("No installation found by IMEI, will create a new installation");
that.create(data, cb);
return;
}
console.log("Found existing installation with id: " + JSON.stringify(result));
result.deviceToken = result.gpsLocation = result.osVersion = result.vendor = result.phoneNumbers = null;
if (data.deviceToken) {
result.deviceToken = data.deviceToken;
}
if (data.gpsLocation) {
result.gpsLocation = data.gpsLocation;
}
if (data.osVersion) {
result.osVersion = data.osVersion;
}
if (data.vendor) {
//result.vendor=data.vendor;
result.vendor = 'jahid';
}
if (data.phoneNumbers) {
result.phoneNumbers = data.phoneNumbers;
}
that.upsert(result, cb);
});
}
}
不幸的是这个代码只被调用一次,我的意思是第一次。之后,永远不会调用此代码。通过查看日志,我确信无疑。它只会第一次打印日志。之后它不会打印任何日志。
知道为什么这个胶水代码只被调用一次?我的目的是拦截安装模型的所有create方法调用。并检查是否已经提供了" IMEI"的条目,如果是,则重复使用。否则创建新的。
提前致谢。
致以最诚挚的问候,
Jahid
答案 0 :(得分:2)
我将从这里开始:
答案 1 :(得分:0)
启动脚本仅在应用程序启动期间运行一次。如果你想要一个每次调用一个函数时触发的函数,使用一个远程钩子或模型钩子。可能是:
...
Installation.beforeRemote('create', ...
...
请参阅http://docs.strongloop.com/display/LB/Adding+logic+to+models了解详情