Sails.js访问模型在服务初始化

问题是:

据我所知,在初始化过程中的sails.js服务在模型之前被初始化。

有没有可能改变这种行为? 在服务之前加载模型。

如果不是,那么在这个服务初始化过程中,我怎样才能从数据库中加载特定的设置来使用它们来构build在某些服务中描述的我的类的实例呢?

一点点坚实的代码:

API /模型/ Model.js

console.log("Model Identified"); module.exports = { attributes: { name: { type: 'string', required: true, size: 15 }, //Some extra secret fields } }; 

API /服务/ 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 ,我结束了这个解决scheme(我还是不太喜欢它,但它工作):

API /服务/ 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 }; 

configuration/ 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()); }); ... 

testing/单元/服务/ MyCoolService.test.js

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

它的工作原理是:服务在引导时被实例化一次,它的实例在任何地方都是可用的。

但对我来说这个解决scheme仍然很奇怪…我仍然不明白如何全局实例化我的服务实例(用于很多控制器),并使其成为最好的方法。