@dannywrayuk/middy-zod-validator
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

Text Logo

Middy Zod Validator

A middy validation plugin that uses zod

version install size downloads


Use a zod schema to check the shape of your lambda Event, Context, Environment and Response.

Install

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

Usage

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!

Contribution

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 :)

License

MIT © Danny Wray

Package Sidebar

Install

npm i @dannywrayuk/middy-zod-validator

Weekly Downloads

21

Version

1.2.0

License

MIT

Unpacked Size

11.9 kB

Total Files

6

Last publish

Collaborators

  • dannywrayuk