-
Notifications
You must be signed in to change notification settings - Fork 394
/
Rule.js
278 lines (225 loc) · 7.13 KB
/
Rule.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
const cloneDeep = require('clone-deep')
const escapeRegex = require('./util/escapeRegex')
const validate = require('./validate')
const knownTypes = ['Object', 'String', 'Number', 'Boolean', 'Array', 'Date']
const isExclusive = ['type', 'uri', 'email']
const mergeRequired = (prev, next) => {
let isRequired = prev._required || next._required
if (!isRequired) {
isRequired = prev._required === false || next._required === false ? false : undefined
}
return isRequired
}
class Rule {
static FIELD_REF = Symbol('FIELD_REF')
static array = def => new Rule(def).type('Array')
static object = def => new Rule(def).type('Object')
static string = def => new Rule(def).type('String')
static number = def => new Rule(def).type('Number')
static boolean = def => new Rule(def).type('Boolean')
static dateTime = def => new Rule(def).type('Date')
static valueOfField = path => ({type: Rule.FIELD_REF, path})
constructor(typeDef) {
this.FIELD_REF = Rule.FIELD_REF
this._typeDef = typeDef
this.reset()
}
// Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class
// eslint-disable-next-line class-methods-use-this
valueOfField(...args) {
return Rule.valueOfField(...args)
}
error(message) {
const rule = this.clone()
rule._level = 'error'
rule._message = message || null
return rule
}
warning(message) {
const rule = this.clone()
rule._level = 'warning'
rule._message = message || null
return rule
}
reset() {
this._type = this._type || null
this._rules = (this._rules || []).filter(rule => rule.flag === 'type')
this._message = null
this._required = undefined
this._level = 'error'
this._fieldRules = undefined
return this
}
isRequired() {
return this._required === true
}
clone() {
const rule = new Rule()
rule._type = this._type
rule._message = this._message
rule._required = this._required
rule._rules = cloneDeep(this._rules)
rule._level = this._level
rule._fieldRules = this._fieldRules
rule._typeDef = this._typeDef
return rule
}
cloneWithRules(rules) {
const rule = this.clone()
const newRules = new Set()
rules.forEach(curr => {
if (curr.flag === 'type') {
rule._type = curr.constraint
}
newRules.add(curr.flag)
})
rule._rules = rule._rules
.filter(curr => {
const disallowDuplicate = isExclusive.includes(curr.flag)
const isDuplicate = newRules.has(curr.flag)
return !(disallowDuplicate && isDuplicate)
})
.concat(rules)
return rule
}
merge(rule) {
if (this._type && rule._type && this._type !== rule._type) {
throw new Error('merge() failed: conflicting types')
}
const newRule = this.cloneWithRules(rule._rules)
newRule._type = this._type || rule._type
newRule._message = this._message || rule._message
newRule._required = mergeRequired(this, rule)
newRule._level = this._level === 'error' ? rule._level : this._level
return newRule
}
validate(value, options = {}) {
return validate(this, value, options)
}
// Validation flag setters
type(targetType) {
const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}`
if (!knownTypes.includes(type)) {
throw new Error(`Unknown type "${targetType}"`)
}
const rule = this.cloneWithRules([{flag: 'type', constraint: type}])
rule._type = type
return rule
}
all(children) {
return this.cloneWithRules([{flag: 'all', constraint: children}])
}
either(children) {
return this.cloneWithRules([{flag: 'either', constraint: children}])
}
// Shared rules
optional() {
const rule = this.cloneWithRules([{flag: 'presence', constraint: 'optional'}])
rule._required = false
return rule
}
required() {
const rule = this.cloneWithRules([{flag: 'presence', constraint: 'required'}])
rule._required = true
return rule
}
custom(fn) {
return this.cloneWithRules([{flag: 'custom', constraint: fn}])
}
min(len) {
return this.cloneWithRules([{flag: 'min', constraint: len}])
}
max(len) {
return this.cloneWithRules([{flag: 'max', constraint: len}])
}
length(len) {
return this.cloneWithRules([{flag: 'length', constraint: len}])
}
valid(value) {
const values = Array.isArray(value) ? value : [value]
return this.cloneWithRules([{flag: 'valid', constraint: values}])
}
// Numbers only
integer() {
return this.cloneWithRules([{flag: 'integer'}])
}
precision(limit) {
return this.cloneWithRules([{flag: 'precision', constraint: limit}])
}
positive() {
return this.cloneWithRules([{flag: 'min', constraint: 0}])
}
negative() {
return this.cloneWithRules([{flag: 'lessThan', constraint: 0}])
}
greaterThan(num) {
return this.cloneWithRules([{flag: 'greaterThan', constraint: num}])
}
lessThan(num) {
return this.cloneWithRules([{flag: 'lessThan', constraint: num}])
}
// String only
uppercase() {
return this.cloneWithRules([{flag: 'stringCasing', constraint: 'uppercase'}])
}
lowercase() {
return this.cloneWithRules([{flag: 'stringCasing', constraint: 'lowercase'}])
}
regex(pattern, name, opts) {
let options = opts || {name}
if (!opts && name && (name.name || name.invert)) {
options = name
}
const constraint = Object.assign({}, options, {pattern})
return this.cloneWithRules([{flag: 'regex', constraint}])
}
email(options) {
return this.cloneWithRules([{flag: 'email', constraint: options}])
}
uri(opts = {}) {
const options = Object.assign(
{scheme: ['http', 'https'], allowRelative: false, relativeOnly: false},
opts
)
const allowedSchemes = Array.isArray(options.scheme) ? options.scheme : [options.scheme]
options.scheme = allowedSchemes.map(scheme => {
const schemeIsString = typeof scheme === 'string'
if (!(scheme instanceof RegExp) && schemeIsString === false) {
throw new Error('scheme must be a RegExp or a String')
}
return schemeIsString ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme
})
if (!options.scheme.length) {
throw new Error('scheme must have at least 1 scheme specified')
}
return this.cloneWithRules([{flag: 'uri', constraint: {options}}])
}
// Array only
unique(comparator) {
return this.cloneWithRules([{flag: 'unique', constraint: comparator}])
}
// Objects only
reference() {
return this.cloneWithRules([{flag: 'reference'}])
}
fields(rules) {
if (this._type !== 'Object') {
throw new Error('fields() can only be called on an object type')
}
const rule = this.cloneWithRules([])
rule._fieldRules = rules
return rule
}
assetRequired() {
const base = getBaseType(this._typeDef)
let assetType = 'Asset'
if (base && ['image', 'file'].includes(base.name)) {
assetType = base.name === 'image' ? 'Image' : 'File'
}
return this.cloneWithRules([{flag: 'assetRequired', constraint: {assetType}}])
}
}
function getBaseType(type) {
return type && type.type ? getBaseType(type.type) : type
}
module.exports = Rule