Skip to content

Instantly share code, notes, and snippets.

@Salakar
Created January 12, 2018 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Salakar/e4bc675cb0f66972875ca5ef2b1b26ce to your computer and use it in GitHub Desktop.
Save Salakar/e4bc675cb0f66972875ca5ef2b1b26ce to your computer and use it in GitHub Desktop.
An example sails hook that allows overriding the bootstrapped sails models
/**
* Modify sails blueprint parse result
* @param req
* @return {*}
*/
function parseBlueprintOptions(req) {
const queryOptions = sails.hooks.blueprints.parseBlueprintOptions(req);
// do blueprint overrides if needed...
return queryOptions;
}
/**
* Example Hook that modifies sails models that are created
*
* @param sails
* @return {{configure: (function()), initialize: (function(Function))}}
*/
module.exports = function modifyModelsHook(sails) {
// keep a ref to the original sails model loader function
const originalLoadModels = sails.modules.loadModels;
// set a custom blueprint parser if needed
sails.config.blueprints.parseBlueprintOptions = parseBlueprintOptions;
return {
configure() {
// Override sails internal loadModels function
// needs to be in configure()
sails.modules.loadModels = function load(cb) {
// call the original sails loadModels function so we have access to it's returned models
originalLoadModels((err, modelDefs) => {
// modelDefs = all the model files from models directory - sails does this
// now modify / return own models for sails to boot
const models = {};
Object.entries(modelDefs).forEach((entry) => {
const [key, model] = entry;
// TODO: modify / don't set the model based on conditions
// i.e.
// if (model.sequelize === true) { }
models[key] = model;
});
// return the models that the sails orm hook will bootstrap / create
// sequelize models not added / removed from the models object we
// create above
cb(err, models);
});
};
},
/**
* Runs when a Sails app loads/lifts.
*
* @param {Function} done
*/
initialize(done) {
return sails.after('hook:orm:loaded', () => {
// do things after ORM loaded if needed ?
done();
});
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment