How come in sails you cannot access other controller methods from within another one?
like this.
module.exports =
findStore: ->
# do somthing
index: ->
@findStore(); # Error: undefined
Compiled
module.exports = {
findStore: function() {},
index: function() {
return this.findStore(); // Error: undefined
}
};
If you can't do this, then why not? how else should I be doing this...
It's slightly annoying when you're just trying to build something quickly, but in the long run it forces good code organization practice (by making it harder to shove all business logic into a controller).
One of the best ways to organize your code in Sails, at least for me and my team, has been to have all the real business logic in Services (/api/services). Those objects can be accessed globally from any controller.
Also, a good practice is working with promises in services (as Sails use them on the model methods)
Just create a Store service (StoreService.js), with your code:
Your Controllers should handle all that is related to requests, calling services, and returning apropriate responses.
For example, in you example, the controller could have this:
That way, you have really simple controllers, and all business logic is managed by services.
You can do something like this:
And to use the function from another controller:
Having the same problem for last few hours. I used the api/services folder. It may not be exactly what you need but it is an option. A good explanation is here. What services would one add to the api/services folder in sails.js
You can use
sails.controllers.yourControllerName.findStore()
the
sails
global object has references to almost everything.A more elegant way to solve this problem is using the keyword
this
before the function name.Example: