forked from koajs/joi-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput-validator.js
50 lines (39 loc) · 1.28 KB
/
output-validator.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
'use strict';
var OutputValidationRule = require('./output-validation-rule');
var assert = require('assert');
module.exports = OutputValidator;
function OutputValidator(output) {
assert.equal('object', typeof output, 'spec.validate.output must be an object');
this.rules = OutputValidator.tokenizeRules(output);
OutputValidator.assertNoOverlappingStatusRules(this.rules);
this.output = output;
}
OutputValidator.tokenizeRules = function tokenizeRules(output) {
return Object.keys(output).map(function createRule(status) {
return new OutputValidationRule(status, output[status]);
});
};
OutputValidator.assertNoOverlappingStatusRules =
function assertNoOverlappingStatusRules(rules) {
for (var i = 0; i < rules.length; ++i) {
var ruleA = rules[i];
for (var j = 0; j < rules.length; ++j) {
if (i === j) continue;
var ruleB = rules[j];
if (ruleA.overlaps(ruleB)) {
throw new Error(
'Output validation rules may not overlap: ' + ruleA + ' <=> ' + ruleB
);
}
}
}
};
OutputValidator.prototype.validate = function(ctx) {
assert(ctx, 'missing request context!');
for (var i = 0; i < this.rules.length; ++i) {
var rule = this.rules[i];
if (rule.matches(ctx)) {
return rule.validateOutput(ctx);
}
}
};