-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (67 loc) · 1.95 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
require('es6-shim');
var validators = require('./lib/validators')
, util = require('util')
, clone = require('clone')
, stringify = require('json-stable-stringify')
, Transform = require("stream").Transform;
/**
* referenced is an object containing for each field having a foreign key
* a key of field.name and a value of an ES6 Set containing all the
* possible values of the field.
*/
function Validator(schema, referenced, options) {
schema.fields = schema.fields || [];
if(arguments.length < 3){
options = referenced;
}
this._referenced = {};
options = clone(options) || {};
options.objectMode = true;
Transform.call(this, options);
this._validator = {};
schema.fields.forEach(function(x){
this._validator[x.name] = validators(x.type);
}, this);
//validate foreign keys
for (var key in referenced){
this._referenced[key] = new Set();
referenced[key].forEach(function(x){
this._referenced[key].add(_checkable(x));
}, this);
}
};
util.inherits(Validator, Transform);
Validator.prototype._transform = function(obj, encoding, callback){
for(var key in obj){
if(key in this._validator){
var inp = obj[key];
try {
obj[key] = this._validator[key](inp);
} catch(e) {
this.emit('error', e);
}
}
//validate foreignkey
if(key in this._referenced){
if(!this._referenced[key].has(_checkable(obj[key]))){
this.emit('error', new Error(inp + ' is not a valid value according to its foreignkey'));
}
}
}
this.push(obj);
callback();
};
/**
* convert x into a value that can be safely (i.e deterministicaly, by
* value...) used in a Set.has(value) test
*/
function _checkable(x){
var type = Object.prototype.toString.call(x);
if ( (type === '[object Object]') || (type === '[object Array]')){
return stringify(x);
} else if (type === '[object Date]'){
return x.getTime();
}
return x;
};
module.exports = Validator;