Extend Lodash in Sails.js with custom functions
Lodash provides a whole bunch of useful core functions to manipulate data in any way, but sometimes those are not enough. Instead of writing helper functions or services in Sails.js, we can simply extend Lodash’s core functions by using mixin (https://lodash.com/docs/#mixin) when including and exposing Lodash to Sails globals.
Sails: 1.1.0
Lodash: 4.17.13
Since Sails exposes Lodash globally, we can find the include of Lodash in the globals config file, located in./config/globals.js
.
module.exports.globals = {
_: require('lodash'),
async: require('async'),
models: true,
sails: true,
};
As you can see, Sails includes the entire Lodash module and makes it globally available via underscore(_)
.
Now _.mixin
will help us extend the core functions by changing global.js
to the following.
const lodash = require('lodash').mixin({});module.exports.globals = {
_: lodash,
async: require('async'),
models: true,
sails: true,
};
The lodash
include moved above module.exports
and calls the mixin
function with an empty object. Lodash won’t complain about the empty object and skips the mixin part.
Let us add our first custom Lodash function, calledsortKeysBy
, which will sort Object properties by its property name.
const lodash = require('lodash').mixin({
sortKeysBy: (object) => {
const keys = Object.keys(object);
const sortedKeys = _.sortBy(keys);
return _.fromPairs(_.map(sortedKeys, key => [key, object[key]]));
},
});module.exports.globals = {
_: lodash,
async: require('async'),
models: true,
sails: true,
};
Now we can use _.sortKeysBy
anywhere in Sails in the same way we use Lodash’s core functions.
sails.log.debug(_.sortKeysBy({ john: 'doe', apple: 'tree' }));// > debug: { apple: ‘tree’, john: ‘doe’ }
It’s also possible to overwrite lodash its core functions by simply using the name of the function you want to overwrite:
isArray: (input) => {
return Object.prototype.toString.call(input) === '[object Array]';
},isObject: (input) => {
return Object.prototype.toString.call(input) === '[object Object]';
},
Cheers \w