Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 868
Abhishek Avatar asked Oct 28 '14 15:10

Abhishek


People also ask

Can one controller call another controller?

Yes, you can call a method of another controller. The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.

How do you make a controller on sails?

There are two ways to create a new controller in Sails: you can use the sails command to generate the scaffolding, or you can simply have the files generated for you.


2 Answers

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.

like image 172
Terry Avatar answered Oct 27 '22 01:10

Terry


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.

like image 39
Flo Ryan Avatar answered Oct 27 '22 00:10

Flo Ryan