【问题标题】:Loopback strange behaviour环回奇怪的行为
【发布时间】:2015-01-28 00:04:27
【问题描述】:

我说的是环回推送组件。我试图拦截“安装”模型的“创建”方法。我的代码看起来像这样 -

server/boot/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);
   });
  }
}

不幸的是,这段代码只被调用了一次,我的意思是第一次。之后,永远不会调用此代码。我通过查看日志确定了。它只在第一次打印日志。之后它不会打印任何日志。

知道为什么这个胶水代码只被调用一次吗?我的意图是拦截安装模型的所有创建方法调用。并检查是否已经有提供的“IMEI”条目,如果有,则重复使用。否则创建新的。

提前致谢。

最好的问候,

贾希德

【问题讨论】:

    标签: loopbackjs strongloop


    【解决方案1】:

    我将从这里开始:

    1. 不要实现自己的拦截机制,而是使用Model Hooks
    2. 查看findOrCreate()方法

    【讨论】:

    • 任何示例如何从 Android 端调用“findOrCreate()”?我的意思不是服务器端,但我需要客户端代码。
    【解决方案2】:

    启动脚本仅在应用程序启动期间运行一次。如果您想要每次调用函数时触发的函数,请使用远程钩子或模型钩子。大概是这样的:

    ...
    Installation.beforeRemote('create', ...
    ...
    

    查看http://docs.strongloop.com/display/LB/Adding+logic+to+models了解更多信息

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多