Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct place to define reusable functions in Sails.js

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

like image 648
Ashish Avatar asked Dec 14 '22 12:12

Ashish


2 Answers

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

like image 188
fsinisi90 Avatar answered Feb 04 '23 03:02

fsinisi90


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

like image 21
Yann Bertrand Avatar answered Feb 04 '23 03:02

Yann Bertrand