validation-result.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Result = exports.validationResult = void 0;
  4. const _ = require("lodash");
  5. const base_1 = require("./base");
  6. const utils_1 = require("./utils");
  7. /**
  8. * Extracts the validation errors of an express request
  9. */
  10. exports.validationResult = Object.assign(withDefaults(), { withDefaults });
  11. /**
  12. * The current state of the validation errors in a request.
  13. */
  14. class Result {
  15. constructor(formatter, errors) {
  16. this.formatter = formatter;
  17. this.errors = errors;
  18. }
  19. /**
  20. * Gets the validation errors as an array.
  21. *
  22. * @param options.onlyFirstError whether only the first error of each
  23. */
  24. array(options) {
  25. return options?.onlyFirstError ? Object.values(this.mapped()) : this.errors.map(this.formatter);
  26. }
  27. /**
  28. * Gets the validation errors as an object.
  29. * If a field has more than one error, only the first one is set in the resulting object.
  30. *
  31. * @returns an object from field name to error
  32. */
  33. mapped() {
  34. return this.errors.reduce((mapping, error) => {
  35. const key = error.type === 'field' ? error.path : `_${error.type}`;
  36. if (!mapping[key]) {
  37. mapping[key] = this.formatter(error);
  38. }
  39. return mapping;
  40. }, {});
  41. }
  42. /**
  43. * Specifies a function to format errors with.
  44. * @param formatter the function to use for formatting errors
  45. * @returns A new {@link Result} instance with the given formatter
  46. */
  47. formatWith(formatter) {
  48. return new Result(formatter, this.errors);
  49. }
  50. /**
  51. * @returns `true` if there are no errors, `false` otherwise
  52. */
  53. isEmpty() {
  54. return this.errors.length === 0;
  55. }
  56. /**
  57. * Throws an error if there are validation errors.
  58. */
  59. throw() {
  60. if (!this.isEmpty()) {
  61. throw Object.assign(new Error(), (0, utils_1.bindAll)(this));
  62. }
  63. }
  64. }
  65. exports.Result = Result;
  66. /**
  67. * Creates a `validationResult`-like function with default options passed to every {@link Result} it
  68. * returns.
  69. */
  70. function withDefaults(options = {}) {
  71. const defaults = {
  72. formatter: error => error,
  73. };
  74. const actualOptions = _.defaults(options, defaults);
  75. return (req) => {
  76. const contexts = req[base_1.contextsKey] || [];
  77. const errors = _.flatMap(contexts, 'errors');
  78. return new Result(actualOptions.formatter, errors);
  79. };
  80. }