-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
400 lines (335 loc) · 10.4 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
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
386
387
388
389
390
391
392
393
394
395
396
397
"use strict";
var _typeToStr = function(typeClass) {
return typeClass.toString().match(/function\s(.*)\(/)[1];
};
/**
* A schema.
*/
var Schema = function(schema) {
if (!schema) {
throw new Error('Schema is empty');
}
this._defaultLimitTypes = [String,Boolean,Number,Date,Array,Object]
this.schema = schema;
}
/**
* Validate an object against this schema.\
*
* If validation fails. The `details` field in the returned `Error` instance will
* be an `Array` containing per-field error messages.
*
* @param {Object} obj Object to validate.
* @param {Object} [options] Additional options.
* @param {Boolean} [options.ignoreMissing] Whether to ignore missing keys.
* @return {Promise}
*/
Schema.prototype.validate = function(obj, options) {
var self = this;
if (!obj) {
throw new Error('Object is empty');
}
options = options || {};
options.ignoreMissing = options.ignoreMissing || false;
var ret = self._doValidate({
schema: {
path: '',
node: self.schema,
},
object: obj,
}, options);
return ret.then(function(failures) {
if (failures.length) {
var e = new Error('Validation failed');
e.failures = failures.map(function(e) {
return e[0] + ': ' + e[1];
});
throw e;
}
});
}
/**
* Validate given object node against given schema node.
* @return {Promise}
*/
Schema.prototype._doValidate = function(params, options) {
var self = this;
var schemaPath = params.schema.path,
schemaNode = params.schema.node,
obj = params.object,
limitTypes = params.limitTypes || this._defaultLimitTypes;
return Promise.all(Object.keys(schemaNode).map(function(key) {
try {
var currentPath = schemaPath + '/' + key,
currentNode = limitTypes.indexOf(schemaNode[key]) > -1
? { type: schemaNode[key] }
: schemaNode[key],
objectNode = obj[key],
currentNodeType = currentNode.type,
currentNodeValidators = currentNode.validate || [];
// if type not set
if (!currentNodeType) {
return Promise.resolve([[currentPath, 'invalid schema']]);
}
// missing?
if (undefined === objectNode) {
var failures = [];
if (currentNode.required && !options.ignoreMissing) {
failures.push([currentPath, 'missing value']);
}
return Promise.resolve(failures);
}
return new Promise(function(resolve, reject) {
var failures = [];
switch (currentNodeType) {
case String:
if ('string' !== typeof objectNode) {
failures.push([currentPath, 'must be a string']);
} else {
if (Array.isArray(currentNode.enum)) {
if (0 > currentNode.enum.indexOf(objectNode)) {
failures.push(
[currentPath, 'must be one of ' + currentNode.enum.join(', ')]
);
}
}
}
break;
case Boolean:
if ('boolean' !== typeof objectNode) {
failures.push([currentPath, 'must be true or false']);
}
break;
case Number:
if ('number' !== typeof objectNode) {
failures.push([currentPath, 'must be a number']);
}
break;
case Date:
case Object:
case Array:
if (!(objectNode instanceof currentNodeType)) {
failures.push([currentPath, 'must be of type ' + _typeToStr(currentNodeType)]);
}
break;
default:
// if value should be an array
if (Array.isArray(currentNodeType)) {
if (!Array.isArray(objectNode)) {
failures.push([currentPath, 'must be an array']);
} else {
var subSchema = currentNodeType[0];
return Promise.all(Object.keys(objectNode).map(function(index) {
var item = objectNode[index];
return self._doValidate({
schema: {
path: currentPath + '/' + index,
node: subSchema,
},
object: item,
}, options);
}))
.then(function(failures) {
resolve([].concat.apply([], failures));
})
.catch(reject);
}
}
// else it must be an object
else {
return self._doValidate({
schema: {
path: currentPath,
node: currentNodeType,
},
object: objectNode,
}, options)
.then(function(failures) {
resolve(failures);
})
.catch(reject);
}
}
return resolve(failures);
})
.then(function(failures) {
return Promise.all(currentNodeValidators.map(function(fn) {
return fn(objectNode).catch(function(err) {
failures.push([currentPath, err.message]);
});
}))
.then(function() {
return failures;
});
});
} catch (err) {
return Promise.reject(err);
}
}))
.then(function(failures) {
return [].concat.apply([], failures);
});
}
/**
* Helper to typeify()
*/
Schema.prototype._doTypeify = function(params) {
var self = this;
var schemaPath = params.schema.path,
schemaNode = params.schema.node,
object = params.object,
result = params.result,
limitTypes = params.limitTypes || this._defaultLimitTypes;
for (var key in schemaNode) {
var currentPath = schemaPath + '/' + key,
currentNode = limitTypes.indexOf(schemaNode[key]) < 0
? schemaNode[key]
: { type: schemaNode[key] },
objectNode = object[key],
currentNodeType = currentNode.type;
// console.log(currentPath, currentNodeType, objectNode);
// if type not set
if (!currentNodeType) {
continue;
}
// missing?
if (undefined === objectNode) {
continue;
}
// null?
if (null === objectNode) {
result[key] = objectNode;
continue;
}
try {
switch (currentNodeType) {
case String:
if (-1 < limitTypes.indexOf(String)) {
if ('string' !== typeof objectNode) {
objectNode = '' + objectNode;
}
}
break;
case Boolean:
if (-1 < limitTypes.indexOf(Boolean) && 'boolean' !== typeof objectNode) {
var tmp = ('' + objectNode).toLowerCase();
if ('false' === tmp || '0' === tmp || 'no' === tmp) {
objectNode = false;
} else if ('true' === tmp || '1' === tmp || 'yes' === tmp) {
objectNode = true;
}
}
break;
case Number:
if (-1 < limitTypes.indexOf(Number) && 'number' !== typeof objectNode) {
var tmp = '' + objectNode;
tmp = (0 <= tmp.indexOf('.'))
? parseFloat(tmp)
: parseInt(tmp);
if (!Number.isNaN(tmp)) {
objectNode = tmp;
}
}
break;
case Date:
if (-1 < limitTypes.indexOf(Date) && !(objectNode instanceof Date)) {
try {
var tmp = new Date(objectNode);
if (0 < tmp) {
objectNode = tmp;
}
} catch (err) {
// do nothing
}
}
break;
case Object:
case Array:
default:
// if value should be an array
if (Array.isArray(currentNodeType)) {
if (Array.isArray(objectNode)) {
var subSchema = currentNodeType[0];
for (var index in objectNode) {
var item = {},
subnode = {};
subnode[index] = {};
subnode[index].type = subSchema;
item[index] = objectNode[index];
self._doTypeify({
schema: {
path: currentPath,
node: subnode,
},
object: item,
result: item,
limitTypes: limitTypes,
});
// overwrite original
objectNode[index] = item[index];
}
}
}
// else it just be an object
else {
self._doTypeify({
schema: {
path: currentPath,
node: currentNodeType,
},
object: objectNode,
result: objectNode,
limitTypes: limitTypes,
});
}
}
} catch (err) {
// do nothing
}
// set final result
result[key] = objectNode;
}
}
/**
* Decode the correct type for given object's properties based on this schema.
*
* This will iterate through the object's properties. If a property path is
* present in the schema then it will attempt to modify the property's value
* such that its runtime type matches what the schema expects for that property.
*
* This method is useful if you have parsed JSON data which you wish to insert,
* but in the case where all the property values are strings and the schema
* expects some of them to be booleans, dates, etc.
*
* Any properties in the object which are not present in the schema are left
* unchanged. And any schema properties not present in the object are ignored.
*
* If `limitTypes` is set then it will only typeify the types given within.
* For example if we only wish to process `Date` types then we would pass
* `[Date]` to `limitTypes`.
*
* @param {Object} obj Object to typeify.
* @param {Object} [options] Additional options.
* @param {Array} [options.limitTypes] Limit type-ification to given types.
* @return {Object} Copy of the original object with new property values.
*/
Schema.prototype.typeify = function(obj, options) {
if (!obj) {
return obj;
}
options = options || {};
var newObj = {};
this._doTypeify({
schema: {
path: '',
node: this.schema,
},
object: obj,
result: newObj,
limitTypes: options.limitTypes,
});
return newObj;
}
module.exports = function(schema) {
return new Schema(schema);
};
exports.Schema = Schema;