Search code examples
node.jsormsails.jshttp-request

Adding missing request parameter before persistance in Sails.JS


Is it possible to "insert" a missing parameter (in case it was not sent), in order to persist them all via req.params.all()?

Currently trying to do so, gets me a no method 'setParameter' error.


Solution

  • It's not possible to add anything into the result of req.params.all() in Sails without implementing custom middleware, since it's parsed at request time and provided to route handlers before any user-level code runs. However, if what you're looking for is default parameter options, in Sails v0.10.x you can use the req.options hash for this. If you wanted to set a default limit for a blueprint "find", for example, you could do the following in your /config/routes.js:

    '/user': {blueprint: 'find', options: {limit: 10}}
    

    Documentation for these options is forthcoming, in the meantime you can examine the source code to see which blueprint options are available.

    For default params in your custom controller actions, you can use options in a similar way:

    '/foo': {controller: 'FooController', action: 'bar', options: {abc: 123}}
    

    and in your action code, check the options:

    bar: function(req, res) {
    
       var abc = req.param('abc') || req.options.abc;
    
    }
    

    This is preferable to messing with req.params.all, because you can tell whether you are using a user-supplied or a default value. But if you really want to alter the params directly, you can do it through custom middleware in /config/express.js:

    customMiddleware: function(app) {
    
       app.use(function(req, res, next) {
    
           // Note: req.params doesn't exist yet because the router middleware
           // hasn't run, but we can add whatever we want to req.query and it
           // will stick as long as it isn't overwritten by a route param or
           // something in req.body.  This is the desired behavior.
           req.query.foo = req.query.foo || 'bar';
           return next();
    
       });
    
    }