Configure the parser with the schema, envelope and whether to safeParse or not
import { z } from 'zod';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import type { SqSEvent } from '@aws-lambda-powertools/parser/types;
import { parser } from '@aws-lambda-powertools/parser';
import { SqsEnvelope } from '@aws-lambda-powertools/parser/envelopes';
const Order = z.object({
orderId: z.string(),
description: z.string(),
});
class Lambda implements 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;
}
}
In case you want to parse the event and handle the error, you can use the safeParse option. The safeParse option will return an object with the parsed event and an error object if the parsing fails.
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import type { SqSEvent, ParsedResult } from '@aws-lambda-powertools/parser/types;
import { z } from 'zod';
import { parser } from '@aws-lambda-powertools/parser';
import { SqsEnvelope } from '@aws-lambda-powertools/parser/envelopes';
const Order = z.object({
orderId: z.string(),
description: z.string(),
}
class Lambda implements LambdaInterface {
@parser({ envelope: SqsEnvelope, schema: OrderSchema, safeParse: true })
public async handler(event: ParsedResult<Order>, _context: unknown): Promise<unknown> {
if (event.success) {
// event.data is the parsed event object of type Order
} else {
// event.error is the error object, you can inspect and recover
// event.originalEvent is the original event that failed to parse
}
}
}
You can also provide an errorHandler callback to intercept parse errors and return a custom response
instead of throwing. If the handler returns undefined, the error is rethrown.
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { z } from 'zod';
import { parser } from '@aws-lambda-powertools/parser';
const Order = z.object({
orderId: z.string(),
description: z.string(),
});
class Lambda implements LambdaInterface {
@parser({ schema: Order, errorHandler: (error) => ({ statusCode: 400, body: error.message }) })
public async handler(event: z.infer<typeof Order>, _context: Context): Promise<unknown> {
return processOrder(event);
}
}
A decorator to parse your event.