1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | var helpers_1 = require("@radial/helpers");
|
4 | var forEach_1 = require("./rules/forEach");
|
5 | var setIn = helpers_1.setInMutable;
|
6 | var ValidationException = (function () {
|
7 | function ValidationException(errors) {
|
8 | this.errors = errors;
|
9 | }
|
10 | return ValidationException;
|
11 | }());
|
12 | exports.ValidationException = ValidationException;
|
13 | function only(value, path, validators, data) {
|
14 | var result = validators.map(function (validator) {
|
15 | var isNil = value === undefined || value === null;
|
16 | if (isNil && validator.name !== 'notBlank' && validator.name !== 'notNull')
|
17 | return Promise.resolve();
|
18 | return Promise.resolve(validator(value, path, data, {}));
|
19 | });
|
20 | return Promise.all(result).then(function (errors) {
|
21 | return errors.filter(function (error) {
|
22 | return error !== undefined && error !== null;
|
23 | });
|
24 | }).then(function (err) {
|
25 | return err.length == 0 ? Promise.resolve() : Promise.reject(err);
|
26 | });
|
27 | }
|
28 | exports.only = only;
|
29 | function validate(data, rules) {
|
30 | if (data === void 0) { data = {}; }
|
31 | if (rules === void 0) { rules = {}; }
|
32 | var errors = {};
|
33 | var results = Object.keys(rules).map(function (key) {
|
34 | var val = helpers_1.getIn(data, key);
|
35 | var rule = rules[key];
|
36 | if (rule instanceof forEach_1.ForEach) {
|
37 | if ((helpers_1.isBlank(val) || !Array.isArray(val)) && rule.nullable === false) {
|
38 | setIn(errors, key, ['This is required']);
|
39 | return Promise.resolve(null);
|
40 | }
|
41 | if (!Array.isArray(val) && rule.nullable)
|
42 | return Promise.resolve(null);
|
43 | var promises = val.map(function (data, index) {
|
44 | var path = key + '.' + index;
|
45 | var promise = Array.isArray(rule.rules) ? only(data, path, rule.rules, val) : validate(data, rule.rules);
|
46 | return promise.catch(function (err) {
|
47 | setIn(errors, path, err.errors || err);
|
48 | });
|
49 | });
|
50 | return Promise.all(promises);
|
51 | }
|
52 | else {
|
53 | return new Promise(function (resolve, reject) {
|
54 | only(val, key, rules[key], data).then(function () {
|
55 | resolve();
|
56 | }, function (e) {
|
57 | setIn(errors, key, e);
|
58 | resolve();
|
59 | });
|
60 | });
|
61 | }
|
62 | });
|
63 | return new Promise(function (resolve, reject) {
|
64 | Promise.all(results).then(function () {
|
65 | if (Object.keys(errors).length == 0) {
|
66 | return resolve();
|
67 | }
|
68 | reject(new ValidationException(errors));
|
69 | });
|
70 | });
|
71 | }
|
72 | exports.validate = validate;
|