-
Notifications
You must be signed in to change notification settings - Fork 8
/
helpers.js
93 lines (79 loc) · 2.12 KB
/
helpers.js
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
83
84
85
86
87
88
89
90
91
92
93
const validator = require('validator')
const toString = Object.prototype.toString
exports.type = function (actual, expected, key, parent) {
if (expected === 'any') return true
if (typeof expected === 'function') {
return expected.call(this, actual, key, parent)
}
return expected === toString.call(actual).match(/^\[object\s(.*)\]$/)[1].toLowerCase()
}
/*
* String
*/
exports.length = function (actual, expected, key, parent) {
if (Array.isArray(expected)) {
const len = actual.length
return len >= expected[0] && len <= expected[1]
}
return actual.length === expected
}
// return true|false
/*
* Number
*/
exports.gt = function (actual, expected, key, parent) {
return actual > expected
}
exports.gte = function (actual, expected, key, parent) {
return actual >= expected
}
exports.lt = function (actual, expected, key, parent) {
return actual < expected
}
exports.lte = function (actual, expected, key, parent) {
return actual <= expected
}
exports.range = function (actual, expected, key, parent) {
return (actual >= expected[0]) && (actual <= expected[1])
}
/*
* Array
*/
exports.enum = function (actual, expected, key, parent) {
return expected.indexOf(actual) !== -1
}
/*
* RegExp
*/
exports.pattern = function (actual, expected, key, parent) {
return expected.test(actual)
}
exports.default = function (actual, expected, key, parent) {
parent[key] = actual != null
? actual
: (typeof expected === 'function' ? expected.apply(this, arguments) : expected)
return true
}
exports.required = function (actual, expected, key, parent) {
return actual != null
}
/*
* common
*/
exports.eq = exports.equal = function (actual, expected, key, parent) {
return actual === expected
}
/*
* validator's `isXxx`
*/
Object.keys(validator)
.filter(name => !!name.match(/^is/))
.forEach(name => {
exports[name] = function (actual, expected, key, parent) {
if (typeof actual !== 'string') {
return false
}
expected = Array.isArray(expected) ? expected : [expected]
return validator[name](actual, ...expected.slice(0, -1)) === expected[expected.length - 1]
}
})