express-validator.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ExpressValidator = void 0;
  4. const matched_data_1 = require("./matched-data");
  5. const check_1 = require("./middlewares/check");
  6. const exact_1 = require("./middlewares/exact");
  7. const one_of_1 = require("./middlewares/one-of");
  8. const schema_1 = require("./middlewares/schema");
  9. const validation_result_1 = require("./validation-result");
  10. /* eslint-enable no-use-before-define */
  11. class ExpressValidator {
  12. constructor(validators, sanitizers, options) {
  13. this.validators = validators;
  14. this.sanitizers = sanitizers;
  15. this.options = options;
  16. /**
  17. * Creates a middleware/validation chain for one or more fields that may be located in
  18. * any of the following:
  19. *
  20. * - `req.body`
  21. * - `req.cookies`
  22. * - `req.headers`
  23. * - `req.params`
  24. * - `req.query`
  25. *
  26. * @param fields a string or array of field names to validate/sanitize
  27. * @param message an error message to use when failed validations don't specify a custom message.
  28. * Defaults to `Invalid Value`.
  29. */
  30. this.check = this.buildCheckFunction(['body', 'cookies', 'headers', 'params', 'query']);
  31. /**
  32. * Same as {@link ExpressValidator.check}, but only validates in `req.body`.
  33. */
  34. this.body = this.buildCheckFunction(['body']);
  35. /**
  36. * Same as {@link ExpressValidator.check}, but only validates in `req.cookies`.
  37. */
  38. this.cookie = this.buildCheckFunction(['cookies']);
  39. /**
  40. * Same as {@link ExpressValidator.check}, but only validates in `req.headers`.
  41. */
  42. this.header = this.buildCheckFunction(['headers']);
  43. /**
  44. * Same as {@link ExpressValidator.check}, but only validates in `req.params`.
  45. */
  46. this.param = this.buildCheckFunction(['params']);
  47. /**
  48. * Same as {@link ExpressValidator.check}, but only validates in `req.query`.
  49. */
  50. this.query = this.buildCheckFunction(['query']);
  51. /**
  52. * Checks whether the request contains exactly only those fields that have been validated.
  53. *
  54. * This method is here for convenience; it does exactly the same as `checkExact`.
  55. *
  56. * @see {@link checkExact}
  57. */
  58. this.checkExact = exact_1.checkExact;
  59. /**
  60. * Creates an express middleware with validations for multiple fields at once in the form of
  61. * a schema object.
  62. *
  63. * @param schema the schema to validate.
  64. * @param defaultLocations which locations to validate in each field. Defaults to every location.
  65. */
  66. // NOTE: This method references its own type, so the type cast is necessary.
  67. this.checkSchema = (0, schema_1.createCheckSchema)((...args) => this.createChain(...args), Object.keys(this.validators || {}), Object.keys(this.sanitizers || {}));
  68. /**
  69. * Extracts the validation errors of an express request using the default error formatter of this
  70. * instance.
  71. *
  72. * @see {@link validationResult()}
  73. * @param req the express request object
  74. * @returns a `Result` which will by default use the error formatter passed when
  75. * instantiating `ExpressValidator`.
  76. */
  77. this.validationResult = (req) => {
  78. const formatter = this.options?.errorFormatter;
  79. const result = (0, validation_result_1.validationResult)(req);
  80. return formatter ? result.formatWith(formatter) : result;
  81. };
  82. this.validatorEntries = Object.entries(validators || {});
  83. this.sanitizerEntries = Object.entries(sanitizers || {});
  84. // Can't use arrow function in the declaration of `buildCheckFunction` due to the following
  85. // error which only happens when tests are run without Jest cache (so CI only):
  86. //
  87. // 'buildCheckFunction' implicitly has type 'any' because it does not have a type annotation
  88. // and is referenced directly or indirectly in its own initializer
  89. this.buildCheckFunction = this.buildCheckFunction.bind(this);
  90. }
  91. createChain(fields = '', locations = [], message) {
  92. const middleware = (0, check_1.check)(fields, locations, message);
  93. const boundValidators = Object.fromEntries(this.validatorEntries.map(([name, fn]) => [name, () => middleware.custom(fn)]));
  94. const boundSanitizers = Object.fromEntries(this.sanitizerEntries.map(([name, fn]) => [name, () => middleware.customSanitizer(fn)]));
  95. return Object.assign(middleware, boundValidators, boundSanitizers);
  96. }
  97. buildCheckFunction(locations) {
  98. return (fields, message) => this.createChain(fields, locations, message);
  99. }
  100. /**
  101. * Creates a middleware that will ensure that at least one of the given validation chains
  102. * or validation chain groups are valid.
  103. *
  104. * If none are, a single error of type `alternative` is added to the request,
  105. * with the errors of each chain made available under the `nestedErrors` property.
  106. *
  107. * @param chains an array of validation chains to check if are valid.
  108. * If any of the items of `chains` is an array of validation chains, then all of them
  109. * must be valid together for the request to be considered valid.
  110. */
  111. oneOf(chains, options) {
  112. return (0, one_of_1.oneOf)(chains, options);
  113. }
  114. /**
  115. * Extracts data validated or sanitized from the request, and builds an object with them.
  116. *
  117. * This method is a shortcut for `matchedData`; it does nothing different than it.
  118. *
  119. * @see {@link matchedData}
  120. */
  121. matchedData(req, options) {
  122. return (0, matched_data_1.matchedData)(req, options);
  123. }
  124. }
  125. exports.ExpressValidator = ExpressValidator;