forked from koajs/joi-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput-validation-rule.ts
77 lines (63 loc) · 1.65 KB
/
output-validation-rule.ts
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
77
import {
IRange,
ValidatorBuilder,
OutputValidation,
IValidationError,
} from './types'
import { rangify } from './helpers'
import { Context } from 'koa'
export class OutputValidationRule<Schema> {
static overlaps<T>(a: OutputValidationRule<T>, b: OutputValidationRule<T>) {
return a.ranges.some(function checkRangeA(rangeA: any) {
return b.ranges.some(function checkRangeB(rangeB: any) {
if (rangeA.upper >= rangeB.lower && rangeA.lower <= rangeB.upper) {
return true
}
return false
})
})
}
private ranges: IRange[] = []
constructor(private status: string, private spec: OutputValidation<Schema>) {
this.ranges = status
.split(',')
.map((s) => s.trim())
.filter(Boolean)
.map(rangify)
}
public overlaps(ruleB: OutputValidationRule<Schema>) {
return OutputValidationRule.overlaps<Schema>(this, ruleB)
}
public matches(status: number) {
for (let range of this.ranges) {
if (status >= range.lower && status <= range.upper) {
return true
}
}
return false
}
public async validateOutput(
ctx: Context,
validatorBuilder: ValidatorBuilder<Schema>
): Promise<IValidationError[] | null> {
let result
if (this.spec.headers) {
const validator = await validatorBuilder(this.spec.headers)
result = await validator(ctx.response.headers)
if (result.error) return result.error
// use casted values
ctx.set(result.value)
}
if (this.spec.body) {
const validator = await validatorBuilder(this.spec.body)
result = await validator(ctx.body)
if (result.error) return result.error
// use casted values
ctx.body = result.value
}
return null
}
toString() {
return this.status
}
}