-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
98 lines (78 loc) · 2.29 KB
/
index.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
#!/usr/bin/env node
var assert = require('assert-plus')
function validator (obj, schema, path) {
assert.object(obj, 'Object to be validate');
assert.object(schema, 'Schema used to validate');
path = path || '';
var errors = [];
// handle array
if(schema.type === 'array') {
// validate type
if(!Array.isArray(obj)) {
var tmp_path = path === '' ? 'Array' : path;
errors.push('validate type failed for ' + tmp_path);
return errors;
}
// validate nested array
if(schema.elemSchema && obj.length) {
obj.forEach(function(elem, i) {
errors = errors.concat(validator(elem, schema.elemSchema, prefix(path || 'Array', i)));
});
return errors;
}
// validate simple array
if(schema.elemType && obj.length) {
obj.forEach(function(elem, i) {
if(typeof(elem) !== schema.elemType) {
errors.push('validate type failed for ' + prefix(path || 'Array', i));
}
});
return errors;
}
}
// handle object
for(var key in schema) {
var type = schema[key]['type'];
var required = schema[key]['required'];
var elemType = schema[key]['elemType'];
var elemSchema = schema[key]['elemSchema'];
var value = obj[key];
assert.optionalString(type, key + '.type');
assert.optionalBool(required, key + '.required');
assert.optionalString(elemType, key + '.elemType');
assert.optionalObject(elemSchema, key + '.elemSchema');
// check if is required
if(required === false) {
continue;
}
// check allowed && existed
if(!isExist(value, type)) {
errors.push('validate exist failed for ' + prefix(path, key));
continue;
}
// handle nested object
if(typeof(value) === 'object') {
errors = errors.concat(validator(value, schema[key], prefix(path, key)));
continue;
}
// check for type
if(type && typeof(value) !== type) {
errors.push('validate type failed for ' + prefix(path, key));
}
// check for exist
if(!(required && isExist(value, type))) {
errors.push('validate value failed for ' + prefix(path, key));
}
}
return errors;
}
function isExist (value, type) {
return !!value ||
(value === 0 && type === 'number') ||
(value === '' && type === 'string') ||
(value === false && type === 'boolean');
}
function prefix (prefix, key) {
return prefix ? (prefix + '.' + key) : key;
}
module.exports = validator;