I have lots of functions, lets say P(), Q(), R(), S(), T() and I have 3 controllers, A, B and C.
Controller A uses P() and Q(), B uses R(), S() and T() while C uses P(), Q() and T().
I have already defined the controllers, where should I define functions (which folder)? how do I include them in the controllers?
The functions maybe used in some other controllers later (and they can be categorized).
In Sails 1.0 you should use Helpers instead of Services.
As of v1.0, all Sails apps come with built-in support for helpers, simple utilities that let you share Node.js code in more than one place. This helps you avoid repeating yourself, and makes development more efficient by reducing bugs and minimizing rewrites. Like actions2, this also makes it much easier to create documentation for your app.
You can generate a new helper running the command:
sails generate helper get-current-date
A new file will be created under the helpers
folder. Example:
module.exports = {
friendlyName: 'Get current date',
description: 'Creates a new Date object and returns it',
inputs: {},
exits: {
success: {
outputFriendlyName: 'Current date',
outputType: 'ref'
},
},
fn: async function (inputs, exits) {
return exits.success(new Date());
}
};
Then just use it like sails.helpers.getCurrentDate()
.
You should put them in the services folder. Here is what the docs stipulates:
'Services' are similar to controller actions but are typically used for things that don't nessecarily have to happen between the time when the user sends a request and when the server sends back a response. Any logic that doesn't rely on .req() and .res() can be turned into a service if for no other reason than to keep your controllers clean and managable.
For example, you can create a Utils
service:
// api/services/Utils.js
module.exports.p = function (a, b, c) {
// Do whatever...
};
module.exports.q = function (a, b, c) {
// Do whatever...
return c();
};
// And so on
And use these functions in your controllers like this:
// api/controllers/A.js
module.exports = {
anAction: function (req, res) {
// ...
Utils.p('hello', 1, [123, 456]);
Utils.q('world', 0, function () {
// ...
});
// ...
}
};
You can also access the service functions with sails.services['utils'].theFunctionName()
and replace theFunctionName
by the name of the function you want to use (e.g. p
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With