从控制器方法的sails.js访问控制器方法
如何进入风帆你不能从另一个内部访问其他控制器方法?
喜欢这个。
module.exports = findStore: -> # do somthing index: -> @findStore(); # Error: undefined
编译
module.exports = { findStore: function() {}, index: function() { return this.findStore(); // Error: undefined } };
如果你不能这样做,为什么不呢? 我应该怎么做呢…
过去几个小时有同样的问题。 我使用了api / services文件夹。 这可能不是你所需要的,但它是一个选项。 这里有一个很好的解释。 sails.js中的api / services文件夹将添加哪些服务
你可以使用sails.controllers.yourControllerName.findStore()
sails
全局对象几乎引用了所有的东西。
在Sails中组织代码的最好方法之一,至less对我和我的团队来说,一直是在服务(/ api / services)中拥有所有真正的业务逻辑。 这些对象可以从任何控制器全局访问。
另外,一个好的做法是使用服务中的承诺(如Sails在模型方法中使用它们)
只需使用您的代码创build一个Store服务(StoreService.js):
module.exports = { findStore: function(storeId) { // here you call your models, add object security validation, etc... return Store.findOne(storeId); } };
你的控制器应该处理与请求相关的所有事情,调用服务并返回适当的响应。
例如,在你的例子中,控制器可以有这样的:
module.exports = { index: function(req, res) { if(req.param('id')) { StoreService.findStore(req.param('id')) .then(res.ok) .catch(res.serverError); } else { res.badRequest('Missing Store id'); } }, findStore: function(req, res) { if(req.param('id')) { StoreService.findStore(req.param('id')) .then(res.ok) .catch(res.serverError); } else { res.badRequest('Missing Store id'); } }, };
这样,你有真正简单的控制器,所有的业务逻辑是由服务pipe理。
当你试图快速构build某些东西的时候有些恼人,但是从长远来看,这会强制代码组织的实践(把所有的业务逻辑推到一个控制器上)。
解决这个问题的更好方法是在函数名前面使用关键字this
。
例:
one: function() { console.log('First Function'); }, two: function() { // call the function one in the same controller this.one(); }