-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid.js
38 lines (29 loc) · 865 Bytes
/
valid.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
var dot = require('dot-object');
module.exports = function valid(options) {
if (!options || !options.otherwise) {
throw new Error('`otherwise` validation failure handler is missing.');
}
return function (req, res, next) {
var errors = {};
res.error = function error(prop, message, code) {
var list = errors[prop] = errors[prop] || [];
list.push({
message: message,
code: code
});
};
res.nonFieldError = function nonFieldError(message, code) {
return res.error(null, message, code);
}
req.valid = function valid() {
if (Object.keys(errors).length === 0) {
return Promise.resolve();
} else {
dot.object(errors);
options.otherwise(req, req.res, errors);
return new Promise(function() {}); // always pending
}
}
next();
};
};