-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponseBodyValidation.ts
55 lines (44 loc) · 1.98 KB
/
responseBodyValidation.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
import { HttpHandler, HttpResponseInit } from '@azure/functions';
import { AnySchema } from 'joi';
import { ApplicationError } from '../error';
import { BeforeExecutionFunction, isErrorResult } from '../middleware';
export type ResponseBodyValidationOptions = {
shouldThrowOnValidationError?: boolean;
printInputOnValidationError?: boolean;
};
export function responseBodyValidation(
schemas: Record<number, AnySchema>,
options?: ResponseBodyValidationOptions,
): BeforeExecutionFunction<HttpHandler> {
const shouldThrowOnValidationError = options?.shouldThrowOnValidationError ?? false;
const printInputOnValidationError = options?.printInputOnValidationError ?? true;
return async (req, context, result) => {
if (isErrorResult<ReturnType<HttpHandler>>(result)) {
context.info(`Skipping response body validation because the result is faulty`);
return;
}
const httpResponse = result.$result as HttpResponseInit;
const responseStatus = httpResponse.status;
if (!responseStatus || !schemas[responseStatus]) {
if (shouldThrowOnValidationError) {
throw new ApplicationError(
`Response body validation error as there is no schema for status ${responseStatus}`,
500,
);
}
return;
}
const validationResult = schemas[responseStatus].validate(httpResponse.jsonBody);
if (validationResult.error) {
context.error('Response body did not match the given schema:', JSON.stringify(validationResult.error));
if (printInputOnValidationError) {
context.info('Invalid response body:', JSON.stringify(httpResponse.jsonBody));
}
if (shouldThrowOnValidationError) {
throw new ApplicationError('Response body validation error', 500);
}
} else {
context.info('Response body is valid');
}
};
}