-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathschema.js
More file actions
385 lines (331 loc) · 8.74 KB
/
schema.js
File metadata and controls
385 lines (331 loc) · 8.74 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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import dot from '@eivifj/dot';
import typecast from 'typecast';
import Property from './property';
import Messages from './messages';
import Validators from './validators';
import ValidationError from './error';
import { walk, enumerate, join, assign } from './utils';
const typecastObjectPoly = function(val) {
if (val == null) return {};
if (val instanceof Object) return val;
if (typeof val != 'string') return { value: val };
let obj = {};
try {
obj = JSON.parse(val);
} catch (error) {
obj = { value: val };
}
return obj;
};
/**
* A Schema defines the structure that objects should be validated against.
*
* @example
* const post = new Schema({
* title: {
* type: String,
* required: true,
* length: { min: 1, max: 255 }
* },
* content: {
* type: String,
* required: true
* },
* published: {
* type: Date,
* required: true
* },
* keywords: [{ type: String }]
* })
*
* @example
* const author = new Schema({
* name: {
* type: String,
* required: true
* },
* email: {
* type: String,
* required: true
* },
* posts: [post]
* })
*
* @param {Object} [obj] - schema definition
* @param {Object} [opts] - options
* @param {Boolean} [opts.typecast=false] - typecast values before validation
* @param {Boolean} [opts.strip=true] - strip properties not defined in the schema
* @param {Boolean} [opts.strict=false] - validation fails when object contains properties not defined in the schema
*/
export default class Schema {
constructor(obj = {}, opts = {}) {
this.opts = opts;
this.hooks = [];
this.props = {};
this.messages = Object.assign({}, Messages);
this.validators = Object.assign({}, Validators);
this.typecasters = Object.assign({}, { object: typecastObjectPoly, ...typecast });
Object.keys(obj).forEach(k => this.path(k, obj[k]));
}
/**
* Create or update `path` with given `rules`.
*
* @example
* const schema = new Schema()
* schema.path('name.first', { type: String })
* schema.path('name.last').type(String).required()
*
* @param {String} path - full path using dot-notation
* @param {Object|Array|String|Schema|Property} [rules] - rules to apply
* @return {Property}
*/
path(path, rules) {
const parts = path.split('.');
const suffix = parts.pop();
const prefix = parts.join('.');
// Make sure full path is created
if (prefix) {
this.path(prefix);
}
// Array index placeholder
if (suffix === '$') {
this.path(prefix).type(Array);
}
// Catchall Object placeholder
if (suffix === '*') {
this.path(prefix).type(Object);
}
// Nested schema
if (rules instanceof Schema) {
rules.hook((k, v) => this.path(join(k, path), v));
return this.path(path, rules.props);
}
// Return early when given a `Property`
if (rules instanceof Property) {
this.props[path] = rules;
// Notify parents if mounted
this.propagate(path, rules);
return rules;
}
const prop = this.props[path] || new Property(path, this);
this.props[path] = prop;
// Notify parents if mounted
this.propagate(path, prop);
// No rules?
if (!rules) return prop;
// type shorthand
// `{ name: String }`
if (typeof rules == 'string' || typeof rules == 'function') {
prop.type(rules);
return prop;
}
// Allow arrays to be defined implicitly:
// `{ keywords: [String] }`
// `{ keyVal: [[String, Number]] }`
if (Array.isArray(rules)) {
prop.type(Array);
if (rules.length === 1) {
prop.each(rules[0]);
} else {
prop.elements(rules);
}
return prop;
}
const keys = Object.keys(rules);
let nested = false;
// Check for nested objects
for (const key of keys) {
if (typeof prop[key] == 'function') continue;
prop.type(Object);
nested = true;
break;
}
keys.forEach(key => {
const rule = rules[key];
if (nested) {
return this.path(join(key, path), rule);
}
prop[key](rule);
});
return prop;
}
/**
* Typecast given `obj`.
*
* @param {Object} obj - the object to typecast
* @return {Schema}
* @private
*/
typecast(obj) {
for (const [path, prop] of Object.entries(this.props)) {
enumerate(path, obj, (key, value) => {
if (value == null) return;
const cast = prop.typecast(value);
if (cast === value) return;
dot.set(obj, key, cast);
});
}
return this;
}
/**
* Strip all keys not defined in the schema
*
* @param {Object} obj - the object to strip
* @param {String} [prefix]
* @return {Schema}
* @private
*/
strip(obj) {
walk(obj, (path, prop, isCatchall = false) => {
if (this.props[prop]) return true;
if (isCatchall) return false;
dot.delete(obj, path);
return false;
});
return this;
}
/**
* Create errors for all properties that are not defined in the schema
*
* @param {Object} obj - the object to check
* @return {Schema}
* @private
*/
enforce(obj) {
const errors = [];
walk(obj, (path, prop, isCatchall = false) => {
if (this.props[prop]) return true;
if (isCatchall) return false;
const error = new ValidationError(Messages.illegal(path), path);
errors.push(error);
return false;
});
return errors;
}
/**
* Validate given `obj`.
*
* @example
* const schema = new Schema({ name: { required: true }})
* const errors = schema.validate({})
* assert(errors.length == 1)
* assert(errors[0].message == 'name is required')
* assert(errors[0].path == 'name')
*
* @param {Object} obj - the object to validate
* @param {Object} [opts] - options, see [Schema](#schema-1)
* @return {Array}
*/
validate(obj, opts = {}) {
opts = Object.assign(this.opts, opts);
const errors = [];
if (opts.typecast) {
this.typecast(obj);
}
if (opts.strict) {
errors.push(...this.enforce(obj));
}
if (opts.strip !== false) {
this.strip(obj);
}
for (const [path, prop] of Object.entries(this.props)) {
enumerate(path, obj, (key, value) => {
const err = prop.validate(value, obj, key);
if (err) errors.push(err);
});
}
return errors;
}
/**
* Assert that given `obj` is valid.
*
* @example
* const schema = new Schema({ name: String })
* schema.assert({ name: 1 }) // Throws an error
*
* @param {Object} obj
* @param {Object} [opts]
*/
assert(obj, opts) {
const [err] = this.validate(obj, opts);
if (err) throw err;
}
/**
* Override default error messages.
*
* @example
* const hex = (val) => /^0x[0-9a-f]+$/.test(val)
* schema.path('some.path').use({ hex })
* schema.message('hex', path => `${path} must be hexadecimal`)
*
* @example
* schema.message({ hex: path => `${path} must be hexadecimal` })
*
* @param {String|Object} name - name of the validator or an object with name-message pairs
* @param {String|Function} [message] - the message or message generator to use
* @return {Schema}
*/
message(name, message) {
assign(name, message, this.messages);
return this;
}
/**
* Override default validators.
*
* @example
* schema.validator('required', val => val != null)
*
* @example
* schema.validator({ required: val => val != null })
*
* @param {String|Object} name - name of the validator or an object with name-function pairs
* @param {Function} [fn] - the function to use
* @return {Schema}
*/
validator(name, fn) {
assign(name, fn, this.validators);
return this;
}
/**
* Override default typecasters.
*
* @example
* schema.typecaster('SomeClass', val => new SomeClass(val))
*
* @example
* schema.typecaster({ SomeClass: val => new SomeClass(val) })
*
* @param {String|Object} name - name of the validator or an object with name-function pairs
* @param {Function} [fn] - the function to use
* @return {Schema}
*/
typecaster(name, fn) {
assign(name, fn, this.typecasters);
return this;
}
/**
* Accepts a function that is called whenever new props are added.
*
* @param {Function} fn - the function to call
* @return {Schema}
* @private
*/
hook(fn) {
this.hooks.push(fn);
return this;
}
/**
* Notify all subscribers that a property has been added.
*
* @param {String} path - the path of the property
* @param {Property} prop - the new property
* @return {Schema}
* @private
*/
propagate(path, prop) {
this.hooks.forEach(fn => fn(path, prop));
return this;
}
}
// Export ValidationError
Schema.ValidationError = ValidationError;