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