Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mphasize
Created March 2, 2015 12:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mphasize/e9ed62f9d139d2152445 to your computer and use it in GitHub Desktop.
Save mphasize/e9ed62f9d139d2152445 to your computer and use it in GitHub Desktop.
Sails-beforeBlueprint-Policy
/**
* beforeBlueprint
*
* @module :: Policy
* @description :: Simple policy to enable hooks into the model which can act upon req, res objects.
* @docs :: http://sailsjs.org/#!documentation/policies
*
*/
var actionUtil = require( 'sails/lib/hooks/blueprints/actionUtil' );
capitaliseFirstLetter = function ( string ) {
return string.charAt( 0 ).toUpperCase() + string.slice( 1 );
};
module.exports = function ( req, res, next ) {
var Model = actionUtil.parseModel( req );
var blueprint = capitaliseFirstLetter( req.options.action ); // we actually enable this for all actions, not only blueprints
if ( typeof Model[ "controlBefore" + blueprint ] === "function" ) {
var result = Model[ "controlBefore" + blueprint ]( req, res, next );
//next();
} else {
sails.log.debug( 'Policy beforeBlueprint: Model "' + Model.identity + '" has no method controlBefore' + blueprint + '.' );
next();
}
};
// Model defintion api/models/user.js
module.exports = {
attributes: {
name: "string",
"posts": {
collection: "post",
via: "user"
}
},
// beforeFind hook to modify the request before it hits the find blueprint
// other hooks possible, with the naming schema of controlBefore*Blueprint
controlBeforeFind: function ( req, res, next ) {
// modify req.options.where OR req.body OR req.query as you need
next();
}
};
@mphasize
Copy link
Author

mphasize commented Mar 2, 2015

This Policy enables hooks into the Model to provide function that can modify request and response options prior to a Blueprint being executed. Very useful for access control or setting up default associations between models.

@IanVS
Copy link

IanVS commented Mar 2, 2015

Oh man, this is awesome. I've been trying to figure out how to check unique username before user creation, and this looks like the perfect solution.

@harishanchu
Copy link

@IanVS
This is a workaround to implement custom lifecycle callback. To check unique username before user creation you can use the default lifecycle callback beforeCreate in your model like:

beforeCreate: function(values, cb) {
   ...
 },

Please refer docs for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment