forked from aws-powertools/powertools-lambda-typescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
39 lines (38 loc) · 1.2 KB
/
middleware.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
import { SchemaValidationError } from './errors.js';
import type { ValidatorOptions } from './types.js';
import { validate } from './validate.js';
export function validation(options: ValidatorOptions) {
return {
before: async (handler: { event: unknown }) => {
if (options.inboundSchema) {
try {
handler.event = validate({
payload: handler.event,
schema: options.inboundSchema,
envelope: options.envelope,
formats: options.formats,
externalRefs: options.externalRefs,
ajv: options.ajv,
});
} catch (error) {
throw new SchemaValidationError('Inbound validation failed', error);
}
}
},
after: async (handler: { response: unknown }) => {
if (options.outboundSchema) {
try {
handler.response = validate({
payload: handler.response,
schema: options.outboundSchema,
formats: options.formats,
externalRefs: options.externalRefs,
ajv: options.ajv,
});
} catch (error) {
throw new SchemaValidationError('Outbound validation failed', error);
}
}
},
};
}