-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathparser.ts
59 lines (53 loc) · 1.48 KB
/
parser.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
import { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import { Context, Handler } from 'aws-lambda';
import { ZodSchema } from 'zod';
import { type ParserOptions } from './types/ParserOptions.js';
/**
* A decorator to parse your event.
*
* @example
* ```typescript
*
* import { parser } from '@aws-lambda-powertools/parser';
* import { sqsEnvelope } from '@aws-lambda-powertools/parser/envelopes/sqs';
*
*
* const Order = z.object({
* orderId: z.string(),
* description: z.string(),
* }
*
* class Lambda extends LambdaInterface {
*
* @parser({ envelope: sqsEnvelope, schema: OrderSchema })
* public async handler(event: Order, _context: Context): Promise<unknown> {
* // sqs event is parsed and the payload is extracted and parsed
* // apply business logic to your Order event
* const res = processOrder(event);
* return res;
* }
* }
*
* @param options
*/
const parser = <S extends ZodSchema>(
options: ParserOptions<S>
): HandlerMethodDecorator => {
return (_target, _propertyKey, descriptor) => {
const original = descriptor.value!;
const { schema, envelope } = options;
descriptor.value = async function (
this: Handler,
event: unknown,
context: Context,
callback
) {
const parsedEvent = envelope
? envelope(event, schema)
: schema.parse(event);
return original.call(this, parsedEvent, context, callback);
};
return descriptor;
};
};
export { parser };