-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (62 loc) · 1.77 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
var ware = require('ware');
module.exports = function() {
this.validators = [];
this.validator = function(fn, key) {
return this.use(function() {
this.validators.push([fn, key]);
});
};
this.removeValidator = function(fn, key) {
return this.use(function() {
this.validators = this.validators.filter(function(validator, idx) {
return ! (validator[0] === fn && validator[1] === key);
});
});
};
this.validate = function(doc, cb) {
var self = this;
doc.run('validating', function(err, doc) {
if(err) return cb(err);
// Run our own validators first (a model may have
// validators on its root that validate relations
// between elements of the model)
createPipeline(self.validators).run(doc, function(err) {
if(err) return cb(err, doc);
doc.eachAttrAsync(function(name, type, next) {
type.validate(doc.get(name), next);
}, function(err) {
if(err) return cb(err, doc);
doc.run('validated', cb);
});
});
});
return this;
};
this.prototype.validate = function(cb) {
return this.model.validate(this, cb);
};
function wrapValidator(fn, key) {
return function(doc, next) {
fn.length === 0
? handle(fn.call(doc))
: fn.call(doc, handle);
function handle(valid) {
setTimeout(function() {
if(valid === false) {
var err = new Error;
err.key = key;
return next(err);
}
next(null, doc);
});
}
};
}
function createPipeline(validators) {
var pipeline = ware();
validators.forEach(function(validator) {
pipeline.use(wrapValidator(validator[0], validator[1]));
});
return pipeline;
}
};