-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathresponse-validator.ts
More file actions
96 lines (74 loc) · 2.28 KB
/
response-validator.ts
File metadata and controls
96 lines (74 loc) · 2.28 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import Ajv from "ajv";
import type { OpenApiOperation } from "../counterfact-types/index.js";
import type { CounterfactResponseObject } from "./registry.js";
const ajv = new Ajv({
allErrors: true,
strict: false,
coerceTypes: false,
});
export interface ResponseValidationResult {
errors: string[];
valid: boolean;
}
export function validateResponse(
operation: OpenApiOperation | undefined,
response: CounterfactResponseObject,
): ResponseValidationResult {
if (!operation) {
return { errors: [], valid: true };
}
const errors: string[] = [];
const statusKey =
response.status !== undefined ? String(response.status) : undefined;
const responseSpec =
(statusKey !== undefined ? operation.responses[statusKey] : undefined) ??
operation.responses.default;
if (!responseSpec) {
return { errors: [], valid: true };
}
const specHeaders = responseSpec.headers ?? {};
const actualHeaders = response.headers ?? {};
for (const [name, headerSpec] of Object.entries(specHeaders)) {
const actualValue =
actualHeaders[name] ?? actualHeaders[name.toLowerCase()];
if (headerSpec.required === true && actualValue === undefined) {
errors.push(`response header '${name}' is required`);
continue;
}
if (actualValue !== undefined && headerSpec.schema !== undefined) {
const coercedValue =
typeof actualValue === "string"
? coerceHeaderValue(actualValue, headerSpec.schema)
: actualValue;
const valid = ajv.validate(headerSpec.schema, coercedValue);
if (!valid && ajv.errors) {
for (const error of ajv.errors) {
const path = error.instancePath ?? "";
errors.push(
`response header '${name}'${path} ${error.message ?? "is invalid"}`,
);
}
}
}
}
return {
errors,
valid: errors.length === 0,
};
}
function coerceHeaderValue(
value: string,
schema: { [key: string]: unknown },
): unknown {
const type = schema.type as string | undefined;
if (type === "integer" || type === "number") {
const num = Number(value);
return Number.isNaN(num) ? value : num;
}
if (type === "boolean") {
if (value === "true") return true;
if (value === "false") return false;
return value;
}
return value;
}