Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practie to require a module within Sails.js globally?

I am currently building out the Authentication piece of my Sails.js app, using bcrypt to hash my passwords. Everything is working well, here is a sample of the implementation thus far:

beforeCreate: function (values, next) {

    require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {

        if (err) return next(err);

        values.password = encryptedPassword;
        next();

    });

}

Now, both in my model and in my controller, I am using require('bcrypt') or var bcrypt = require('bcrypt'); so I can use it within my class.

I am looking for a better practice way of defining var bcrypt = require('bcrypt'); once and globally so that I can simply use the bcrypt variable whenever I need to (inside other models or controllers).

I am inclined to believe that Sails.js already has something in place for that? If not, what do you suggest the best route of implementation? In the end, I am looking for best practice.

Thanks in advance!

like image 233
Brimstone Avatar asked Jan 13 '14 17:01

Brimstone


People also ask

Is sails a good framework?

Introducing Sails.js It resembles the MVC architecture from such frameworks as Ruby on Rails, but with improved support for the more data-oriented modern style of developing web apps. It is also excellent for building real-time features like live chat. In the same way, Sails. js works well with Backbone and Angular.

Is sails JS popular?

js apps in a matter of weeks, not months. Sails is the most popular MVC framework for Node. js, designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture.

Where does node js require look for modules?

Node will look for your modules in special folders named node_modules . A node_modules folder can be on the same level as the current file, or higher up in the directory chain. Node will walk up the directory chain, looking through each node_modules until it finds the module you tried to load.

Can we use node modules in JavaScript?

Include Your Own Module Now you can include and use the module in any of your Node.js files.


1 Answers

You can also do this by utilizing globals

module.exports.globals = {
    bcrypt : require('bcrypt')
}

and in the application code, refer it like below

sails.config.globals.bcrypt.hash(password, saltRounds, function (err, hash) {
    if (!err) {
      sails.config.globals.logger.info('creatHash-hash-->', hash);
      return cb(null, hash);
    } else {
      return cb(err);
    }
  });
like image 185
Shiven Kumar Avatar answered Sep 28 '22 05:09

Shiven Kumar