簡體   English   中英

服務初始化上的Sails.js訪問模型

[英]Sails.js Access Model on Service initialization

問題:

據我在sails.js中了解,在初始化過程中,服務是在Models之前初始化的。

有可能改變這種行為嗎? 使模型在服務之前加載。

如果不是,那么在此服務初始化期間,如何從數據庫中加載特定設置以使用它們來構建某個服務中描述的類的實例?

一點代碼以提高穩定性:

api / models / Model.js

console.log("Model Identified");

module.exports = {
    attributes: {
        name: { type: 'string', required: true, size: 15 },
        //Some extra secret fields
    }
};

...

api / services / MyCoolService.js

console.log('service inits');

function MyCoolService(options){
    //some extraordinary constructor logic may be ommited
}

MyCoolService.prototype.setOptions = function(options){
    //Set values for MyCoolService fields.
}

//Some other methods

var myCoolServiceWithSettingsFromDb = new MyCoolService();

//That's the place
model.findOne(sails.config.myApplication.settingsId).exec(function(err,result){
    if(!err)
        myCoolServiceWithSettingsFromDb.setOptions(result);
});

module.exports = myCoolServiceWithSettingsFromDb;

這是因為你在服務實例對象與構造函數需要sails是不存在的。 嘗試在MyCoolService使用它;

module.exports = {
  someOption: null,
  method: function () {
    var that = this;
    sails.models.model.findOne(sails.config.myApplication.settingsId)
      .exec(function (err, result) {
        if (!err)
          that.someOption = result;
      });
  }
};

該方法可以由sails.services.mycoolservice.method()或簡單地MyCoolService.method()調用,以從數據庫中為您的服務提供一些選項。

如果要在Sails啟動時啟動它們,請在config/bootstrap.js調用該方法

多虧了Andi Nugroho Dirgantara ,我最終得到了這個解決方案(我仍然不太喜歡它,但是它有效):

api / services / MyCoolService.js

console.log('service inits');

function MyCoolService(options){
    //some extraordinary constructor logic may be ommited
}

//All the same as in question

//The instance
var instance;

module.exports = module.exports = {
    init: function(options) {
        instance = new MyCoolService(options);
    },
    get: function() {
        return instance;
    },
    constructor: MyCoolService
};

config / bootstrap.js

...
Model.findOrCreate({ id: 1 }, sails.config.someDefaultSettings).exec(function(err, result) {
    if (err)
        return sails.log.error(err);
    result = result || sails.config.someDefaultSettings;
    MyCoolService.init(result);
    return sails.log.verbose("MyCoolService Created: ", TbcPaymentProcessorService.get());
});
...

測試/單位/服務/MyCoolService.test.js

...
describe('MyCoolService', function() {

    it('check MyCoolService', function(done) {
        assert.notDeepEqual(MyCoolService.get(), sails.config.someDefaultSettings);
        done();
    });

});
...

它的工作原理:該服務在引導時實例化一次,並且它的實例在任何地方都可用。

但是對我來說,這種解決方案仍然很奇怪……我仍然不了解如何全局實例化我的服務實例(供許多控制器使用)並使其成為最佳方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM