-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequestBodyValidation.ts
More file actions
63 lines (52 loc) · 2.43 KB
/
requestBodyValidation.ts
File metadata and controls
63 lines (52 loc) · 2.43 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
import { HttpHandler } from '@azure/functions';
import { AnySchema, ValidationOptions } from 'joi';
import { ApplicationError } from '../error';
import { BeforeExecutionFunction, isErrorResult } from '../middleware';
export type RequestBodyValidationOptions = {
shouldThrowOnValidationError?: boolean;
transformErrorMessage?: (message: string) => unknown;
printInputOnValidationError?: boolean;
joiValidationOptions?: ValidationOptions;
};
export function requestBodyValidation(
schema: AnySchema,
options?: RequestBodyValidationOptions,
): BeforeExecutionFunction<HttpHandler> {
const shouldThrowOnValidationError = options?.shouldThrowOnValidationError ?? true;
const transformErrorMessage = options?.transformErrorMessage ?? ((message: string) => ({ message }));
const printInputOnValidationError = options?.printInputOnValidationError ?? true;
return async (req, context, result) => {
if (isErrorResult<ReturnType<HttpHandler>>(result)) {
context.info('Skipping request body validation because the result is faulty');
return;
}
const requestBody = await req
.clone()
.json()
.catch((error) => {
context.error('Error during request body validation:', error);
if (error instanceof SyntaxError || error?.name === 'SyntaxError') {
throw new ApplicationError('Request body contains invalid json', 400, {
message: 'Request body contains invalid json',
});
}
throw new ApplicationError('Internal server error', 500, { message: 'Internal server error' });
});
const validationResult = schema.validate(requestBody, options?.joiValidationOptions);
if (validationResult.error) {
context.error('Request body did not match the given schema:', JSON.stringify(validationResult.error));
if (printInputOnValidationError) {
context.info('Invalid request body:', JSON.stringify(requestBody));
}
if (shouldThrowOnValidationError) {
throw new ApplicationError(
'Request body validation error',
400,
transformErrorMessage(validationResult.error.message),
);
}
} else {
context.info('Request body is valid');
}
};
}