sails.js access controller method from controller method

Viewed 24046

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...

7 Answers

I would like to suggest a solution that works but not the best possible way to do it. We can use bind function to bind the context with the calling source as shown below :

generateUrl is present in the Controller A

function generateUrl(){
  return 'www.google.com';
}

get URL is another method in Controller A

getURL(){
  A.generateURL.bind(A.generateURL) //func call with optional arg
}

I hope this helps!

You can do something like this:

//ArticleController
module.exports = {
  findStore: async () => {
    return await findStoreFunc(req.param('id'));
  },
  index: async () => {
    ...
    return await findStoreFunc(id);
  }
};

const findStoreFunc = async (id) => {...}

And to use the function from another controller:

const ArticleController = require('./ArticleController');
//CustomerController
module.exports = {
  index: async () => {
    ...
    let article = await ArticleController.findStore(id);
    ...
  }
};
Related