Reputation: 3912
Getting my hand dirty in Sail.js (and node).
Versions
$ sails --version
1.2.4
$ node --version
v12.16.1
My first sails controller (an example) is as follows:
// MyController
// MyController.js
module.exports = {
sum_it: function (a, b) {
return (a + b);
},
minus_it: function (a, b) {
return (a - b);
},
process_it: function (req, res) {
let i = 12;
let j = 4;
do_what = "sum"; //this will be an input extracted from req
if (do_what == "sum") {
let result = this.sum_it(i, j); //"this" doesn't work????
} else {
let result = this.minus_it(i, j); //"this" doesn't work????
}
console.log(result);
return res.send(result);
}
};
My intention is to have few functions defined within that controller itself as they would be ONLY used under this controller. I used this.sum_it(i, j)
this.minus_it(i, j)
and both of them don't work.
What is the best way to have multiple functions in the controller and call them within that controller file (assuming those functions are too specific to that controller and hence, no need to take them out and put in the other helper files)?
Upvotes: 2
Views: 1366
Reputation: 994
The way you have to think about it is like this: when Sails runs, it compiles all your controllers, services, helpers, etc and sets all the routes using an internal Express application, so, the concept of "this" inside controllers, services, helpers doesn't work.
For this, sails provides you a globally available object: sails
. Within that object you can find all your runtime variables, controllers, services, etc.
To get access to your particular controller action within a controller, for Sails 0.12, you can do:
sails.controllers.my.sum_it(1,2)
For Sails 1.x, you can do:
sails.getActions()['my/sum_it'](1,2)
Finally, if you don't need to expose those functions as actions, you can just make them functions anyhwere in the file outside the module.exports, and call them without this.
Upvotes: 3