const xss = require('xss');

const sanitizeData = (obj) => {
  if (Array.isArray(obj)) {
    return obj.map(v => sanitizeData(v));
  } else if (obj && typeof obj === 'object') {
    return Object.keys(obj).reduce((result, key) => {
      result[key] = sanitizeData(obj[key]);
      return result;
    }, {});
  } else if (typeof obj === 'string') {
    return xss(obj);
  }
  return obj;
};

module.exports = (req, res, next) => {
  req.body = sanitizeData(req.body);
  req.query = sanitizeData(req.query);
  req.params = sanitizeData(req.params);
  next();
};