Abhishek
Abhishek

Reputation: 2019

Sails call one controller from another controller

I am having two controllers, SocketController and ProjectController
SocketController has method getData(data)
ProjectController has method addProject(data)
I need to call addProject() from getData() method.
I tried using sails.controllers.ProjectController.addProject(data) but I got following error:

Cannot find method addProject of undefined

I searched for alternative ways to call another controller using services in Stack Overflow but that was of no help to me. Is there any other way to get this work?

Upvotes: 5

Views: 7983

Answers (2)

Flo Ryan
Flo Ryan

Reputation: 130

Controller functions are also accessible through the global sails object, without use of require, however a function from ProjectController will be found under:

sails.controllers.project.addProject

instead of

sails.controllers.ProjectController.addProject

Anyways you might want to consider having shared functionality in either services or models, as was pointed out previously.

Upvotes: 5

Terry
Terry

Reputation: 14219

Controllers are just Node modules that export public methods. You can require them like anything else. So assuming your methods are correctly exposed with module.exports, this will work:

/* ProjectController */

module.exports = {
  addProject: function(data) {
    // ...
  }
};

/* SocketController */

// Assuming ProjectController.js exists in the same directory (default for Sails)
var projectController = require('./ProjectController');

module.exports = {
  index: function(req, res) {
    // ...
    projectController.addProject(...);
  }
};

Edit: I will add that using services is a better place to keep common functionality like your example. Services allow complex logic to be decoupled from the controller layer and reused by other areas of the application with ease. Controllers should generally be reserved for handling HTTP requests from the client and passing the data to the service or model layers for manipulating the database. I believe Sails also makes services global by default so you don't have to worry about confusing require paths.

Upvotes: 16

Related Questions