UNPKG

1.58 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const _ = require("lodash");
4const base_1 = require("./base");
5const utils_1 = require("./utils");
6// Assign to a variable so that TS doesn't use its catch all overload, which returns any
7const withWithDefaults = { withDefaults };
8exports.validationResult = Object.assign(withDefaults(), withWithDefaults);
9class 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}
39exports.Result = Result;
40function 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}