Home > Mobile >  ExpressJs Trim middleware for nested req.body data
ExpressJs Trim middleware for nested req.body data

Time:05-11

How could I create a middleware to trim all req.body data even NESTED data?

I also accept a trusted well coded package.

Noting that I am using true here : app.use(bodyParser.urlencoded({ extended: true }));

this code ref question

  trim: (req, res, next) => {
    if (req.method === 'POST') {
      for (const [key, value] of Object.entries(req.body)) {
        if (typeof value === 'string') req.body[key] = value.trim();
      }
    }
    next();
  }

This one will work but not for nested data

CodePudding user response:

One way to achieve this in a single line is to utilise the recursion built into JSON.stringify's replacer functionality, check value is number or string then trim it, then parse the result back into an object.

let obj = {
  "a": "f",
  "b": {
    "c": " g",
    "d": "h",
    "x": {
      "a": [
       '1 ', '2 ', '3 '
      ]
    }
  },
  "e": " value3 "
};

obj = JSON.parse(JSON.stringify(obj, (k, v) => ['string', 'number'].includes(typeof v) ? v.trim() : v))

console.log(obj)

Or you could use a recursive function, which if value is object, array then recall the function, lots of example around on that, do a search.

CodePudding user response:

You could loop through each object and array recursively and trim accordingly

function trim(body) {
  for (const key in body) {
    if (typeof body[key] === "object" || Array.isArray(body[key])) {
      trim(body[key]);
    } else if (typeof body[key] === 'string') {
      body[key] = body[key].trim();
    }
  }
};

handleReq: (req, res, next) => {
  if (req.method === 'POST') {
    trim(req.body);
  }
  next();
}
  • Related