Search code examples
node.jsloopback

Loopback: Apply trim function to all incoming string properties


I would like to trim all the strings that are sent in an HTTP request to my loopback project. There are validators that I can use in the model files, but is there something I can do before the request reaches the model?

Thank You


Solution

  • You can write custom express middleware to trim your request data fields.

    var trimmer = function(req, res, next){
      req.body = _.object(_.map(req.body, function (value, key) {
        return [key, value.trim()];
      }));
      next();
    }
    
    app.use(trimmer);
    

    Follow this link for better understanding.