2014-11-22 191 views
1

我在說迴環推送組件。我試圖攔截「安裝」模型的「創建」方法。我的代碼看起來是這樣的 -迴環奇怪行爲

服務器的/ 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」的條目,如果是,則重新使用該條目。否則,創建新的。

在此先感謝。

最好的問候,

Jahid

回答

2

我會在這裏下手爲:

  1. ,而不是實現自己的攔截機制使用Model Hooks
  2. 退房findOrCreate()方法
+0

任何例子,我怎麼能叫「findOrCreate()」?我的意思不是服務器端,但我需要客戶端代碼。 – 2014-11-23 10:01:07

0

boot sc在應用程序啓動過程中,ript只能運行一次。如果您想要一個每次調用函數都會觸發的函數,請使用遠程鉤子或模型鉤子。大概沿着線的東西:

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

看到http://docs.strongloop.com/display/LB/Adding+logic+to+models從Android的側面更多信息

+0

嗨,根據這個鏈接 http://docs.strongloop.com/display/public/LB/Customizing+models (在頁面底部),這是重載內置方法的建議方式。 – 2014-11-23 09:56:36