UNPKG

1.5 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.Result = exports.validationResult = void 0;
4const _ = require("lodash");
5const base_1 = require("./base");
6const utils_1 = require("./utils");
7exports.validationResult = Object.assign(withDefaults(), { withDefaults });
8class Result {
9 constructor(formatter, errors) {
10 this.formatter = formatter;
11 this.errors = errors;
12 }
13 array(options) {
14 return options && options.onlyFirstError
15 ? Object.values(this.mapped())
16 : this.errors.map(this.formatter);
17 }
18 mapped() {
19 return this.errors.reduce((mapping, error) => {
20 if (!mapping[error.param]) {
21 mapping[error.param] = this.formatter(error);
22 }
23 return mapping;
24 }, {});
25 }
26 formatWith(formatter) {
27 return new Result(formatter, this.errors);
28 }
29 isEmpty() {
30 return this.errors.length === 0;
31 }
32 throw() {
33 if (!this.isEmpty()) {
34 throw Object.assign(new Error(), utils_1.bindAll(this));
35 }
36 }
37}
38exports.Result = Result;
39function withDefaults(options = {}) {
40 const defaults = {
41 formatter: error => error,
42 };
43 const actualOptions = _.defaults(options, defaults);
44 return (req) => {
45 const contexts = req[base_1.contextsKey] || [];
46 const errors = _.flatMap(contexts, 'errors');
47 return new Result(actualOptions.formatter, errors);
48 };
49}