schema.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const { isValidator } = require('../utils/filters');
  2. const check = require('./check');
  3. const validLocations = ['body', 'cookies', 'headers', 'params', 'query'];
  4. const notValidators = ['errorMessage', 'in'];
  5. module.exports = (
  6. schema,
  7. defaultLocations = validLocations,
  8. chainCreator = check
  9. ) => Object.keys(schema).map(field => {
  10. const config = schema[field];
  11. const chain = chainCreator(
  12. field,
  13. ensureLocations(config, defaultLocations),
  14. config.errorMessage
  15. );
  16. Object.keys(config)
  17. .filter(method => config[method] && !notValidators.includes(method))
  18. .forEach(method => {
  19. if (typeof chain[method] !== 'function') {
  20. console.warn(`express-validator: a validator with name ${method} does not exist`);
  21. return;
  22. }
  23. const methodCfg = config[method];
  24. let options = methodCfg.options || [];
  25. if (options != null && !Array.isArray(options)) {
  26. options = [options];
  27. }
  28. const methodIsValidator = isValidator(method) || method === 'custom' || method === 'exists';
  29. methodIsValidator && methodCfg.negated && chain.not();
  30. chain[method](...options);
  31. methodIsValidator && chain.withMessage(methodCfg.errorMessage);
  32. });
  33. return chain;
  34. });
  35. function ensureLocations(config, defaults) {
  36. const locations = (Array.isArray(config.in) ? config.in : [config.in]).filter(Boolean);
  37. const actualLocations = locations.length ? locations : defaults;
  38. return actualLocations.filter(location => validLocations.includes(location));
  39. }