A middy validation plugin that uses zod
Use a zod schema to check the shape of your lambda Event, Context, Environment and Response.
Use your favourite package manager
Using npm:
$ npm install @dannywrayuk/middy-zod-validator
Using yarn:
$ yarn add @dannywrayuk/middy-zod-validator
Using pnpm:
$ pnpm add @dannywrayuk/middy-zod-validator
After installation, slot it right into your middy config and pass it a schema.
export const eventSchema = z.object({
body: z
.object({
HelloWorld: z.string(),
})
.strict(),
});
export const handler = middy(lambdaFunction).use(
zodValidator({
eventSchema,
})
);
Keep your schema alongside your lambda function to type it appropriately
import { Handler } from "aws-lambda";
export const eventSchema = z.object({
body: z
.object({
HelloWorld: z.string(),
})
.strict(),
});
type Event = z.infer<typeof eventSchema>;
export const lambdaFunction: Handler<Event> = async (event) => {
/// ...
};
You can optionally combine this with AWS types using the provided Overwrite
type
import { Overwrite } from "@dannywrayuk/middy-zod-validator";
import { APIGatewayProxyEvent, Handler } from "aws-lambda";
export const eventSchema = z.object({
body: z
.object({
HelloWorld: z.string(),
})
.strict(),
});
type Event = Overwrite<APIGatewayProxyEvent, z.infer<typeof eventSchema>>;
export const lambdaFunction: Handler<Event> = async (event) => {
/// ...
};
This way your lambda is secure at runtime and compile time!
If there is an option or feature you would like to see, please feel free to raise an issue or open a pull request. Contributions are welcome :)
MIT © Danny Wray