Skip to content

Instantly share code, notes, and snippets.

@hussainb
Forked from mphasize/beforeBlueprint.js
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save hussainb/89d0435f5bf6e7c83407 to your computer and use it in GitHub Desktop.

Select an option

Save hussainb/89d0435f5bf6e7c83407 to your computer and use it in GitHub Desktop.

Revisions

  1. @mphasize mphasize created this gist Mar 2, 2015.
    29 changes: 29 additions & 0 deletions beforeBlueprint.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    /**
    * 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();
    }

    };
    19 changes: 19 additions & 0 deletions user.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    // 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();
    }
    };