forked from koajs/joi-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output-validator.js
51 lines (40 loc) · 1.3 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
51
'use strict';
const OutputValidationRule = require('./output-validation-rule');
const 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) {
function createRule(status) {
return new OutputValidationRule(status, output[status]);
}
return Object.keys(output).map(createRule);
};
OutputValidator.assertNoOverlappingStatusRules =
function assertNoOverlappingStatusRules(rules) {
for (let i = 0; i < rules.length; ++i) {
const ruleA = rules[i];
for (let j = 0; j < rules.length; ++j) {
if (i === j) continue;
const 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 (let i = 0; i < this.rules.length; ++i) {
const rule = this.rules[i];
if (rule.matches(ctx)) {
return rule.validateOutput(ctx);
}
}
};