0

Is there any best practice how to implement controller chaining in Sails.js? For example I have controller like this:

FirstController.js

var FirstController = {
  getPage: function(req, res){
    var page = 1;
    res.json({
      page: page
    });
  }
};

SecondController.js

var SecondController = {
  getPageSecond: function(req, res){
    //how to call FirstController and then use that result?
  }
};

I usually use Function Constructor to create Constructor first then my controller can call it, but is it the best way? Sometimes I also have to "chaining" blueprint's action, so I re create blueprint and make it become method in my Constructor. Is there any best practice how to make our controller to be more reusable?

Andi N. Dirgantara
  • 2,050
  • 13
  • 20
  • 1
    could you elaborate on why do you need this? Usually there should be no need to access other controllers. It seems like you try to create separate controller for each page. I would suggest creating some universal pageController and then create a Model which would store information about each page. Then you could access as many pages as possible from that Model from any controller. – Martin Malinda Jan 09 '15 at 16:37
  • The `var page` is just an example. I have many use case that need to call other controller like: 1. I need to `find` some models using blueprint API and then I need to modified the JSON result not just an array but with some meta data. 2. I have an `update` method in my controller. But I also need to have `updateCart` which is not only update, but when this controller is called, it will `update` and then give information in cart model. Basically is there any best practice of how to chainning controller? Or is that not a good idea, so I have miss conception about `controller`? – Andi N. Dirgantara Jan 10 '15 at 02:38

1 Answers1

1

Check this thread: sails.js access controller method from controller method

So in your case you could do something like

sails.controllers.update.updateCart()

I havent used anything like that so far though, because I tend to move a lot of logic to policies and services.

For example addMetadata could be a service, which would accept raw data and metadata and handed back a new object. And you could use this service from multiple controllers.

Community
  • 1
  • 1
Martin Malinda
  • 1,573
  • 11
  • 20