sails.js access controller method from controller method

You can use sails.controllers.yourControllerName.findStore()

the sails global object has references to almost everything.


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:

module.exports = {
  findStore: function(storeId) {
    // here you call your models, add object security validation, etc...
    return Store.findOne(storeId);
  }
};

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:

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');
    }
  },
};

That way, you have really simple controllers, and all business logic is managed by services.