-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
75 lines (66 loc) · 2.11 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
'use strict';
var VALIDATION_AREAS = {
params: 'Invalid request parameters',
query: 'Invalid query string',
body: 'Invalid request payload',
headers: 'Invalid request headers'
};
module.exports = function(checks) {
// first validate the middleware options
validateOptions(checks);
// return actual middleware
// unwind loop for better performance
return function(req, res, next) {
var errors = [];
var collectedDetails = [];
var collectedAreas = [];
Object.keys(VALIDATION_AREAS).forEach(function(area) {
var err = errorsFrom(checks, req, area);
if (err) {
errors.push(err);
collectedAreas.push(area);
Array.prototype.push.apply(collectedDetails, err.details);
}
});
if (errors.length > 1) {
var msg = 'There were combined errors in ' + (collectedAreas.join(', ')) + '.';
var err = new Error(msg);
err.details = collectedDetails;
next(err);
} else {
next(errors[0]);
}
};
};
module.exports.setValidationArea = function(name, errorString) {
VALIDATION_AREAS[name] = errorString;
};
function validateOptions(checks) {
var validChecks = 0;
Object.keys(VALIDATION_AREAS).forEach(function(area) {
var matcher = checks[area];
if (matcher) {
if (isMatcher(matcher)) ++validChecks;
else throw new Error(area + ' should be a valid matcher');
}
});
if (validChecks === 0) {
var keys = Object.keys(VALIDATION_AREAS).join(',');
throw new Error('Specify at least one validation from: ' + keys);
}
}
function isMatcher(check) {
var fn = check.match;
return fn && (typeof fn === 'function') && (fn.length >= 1);
}
function errorsFrom(checks, req, area) {
if (checks[area]) {
var result = checks[area].match(area, req[area]);
if (result.length > 0) {
var err = new Error(VALIDATION_AREAS[area]);
err.details = result;
return err;
}
}
return null;
}