forked from davidmenger/is-okay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
82 lines (70 loc) · 1.68 KB
/
main.js
File metadata and controls
82 lines (70 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* @author David Menger
*/
'use strict';
const ValidationError = require('./src/ValidationError');
const traverse = require('./src/traverse');
const Rule = require('./src/Rule');
/**
* @typedef {Error} ValidationError
* @prop {string} invalidKey
* @prop {number} status
* @prop {number} statusCode
*/
class Validator {
constructor () {
this.rules = [];
}
/**
*
* @param {string} path
* @returns {Rule}
*/
required (path) {
const rule = new Rule(path, true);
this.rules.push(rule);
return rule;
}
/**
*
* @param {string} path
* @returns {Rule}
*/
optional (path) {
const rule = new Rule(path, false);
this.rules.push(rule);
return rule;
}
/**
*
* @param {string} path
* @returns {Rule}
*/
nullable (path) {
const rule = new Rule(path, false, true);
this.rules.push(rule);
return rule;
}
/**
*
* @template T
* @param {T:Object} data
* @param {boolean} makeRootOptional - make all root attributes optional (usefull for updates)
* @returns {T}
* @throws {ValidationError}
*/
okay (data, makeRootOptional = false) {
const ret = {};
this.rules.forEach(rule => this._validateRule(rule, data, ret, makeRootOptional));
return ret;
}
_validateRule (rule, data, ret, makeRootOptional) {
traverse(rule._path, (value, key) => rule._validate(value, key, makeRootOptional), data, ret, '');
}
}
function isOkay () {
return new Validator();
}
isOkay.ValidationError = ValidationError;
isOkay.Validator = Validator;
module.exports = isOkay;