middy middleware that uses standard schema validation
npm install middy-standard-schema
A Standard-Schema based Middy Validator
``bash`
npm install middy-standard-schema
After installation, use as a standard middy middleware with any compatible schema.
`typescript
import middy from "@middy/core";
import httpErrorHandler from "@middy/http-error-handler";
import z from "zod";
export const eventSchema = z.object({
body: z.object({
HelloWorld: z.string(),
}),
});
export const handler = middy()
.use(httpErrorHandler())
.use(standardSchemaValidator({ eventSchema }))
.handler(lambdaFunction);
`
Whether it's Zod, Arktype, Valibot, Joi, Yup, or any other compatible library, middy-standard-schema works without any further configuration.
`typescript
import z from "zod";
import { type } from "arktype";
import * as v from "valibot";
middy()
.use(standardSchemaValidator({ eventSchema: z.object() }))
.use(standardSchemaValidator({ eventSchema: type({}) }))
.use(standardSchemaValidator({ eventSchema: v.object({}) }))
.handler(lamdaFunction);
`
`typescript
const eventSchema = z.looseObject({
queryStringParameters: z.looseObject({ search: z.string() }),
});
middy
.use(standardSchemaValidator({ eventSchema }))
.handler((event) => {
event.queryStringParameters.search;
// ^? (property) search: string
event.queryStringParameters.unspecified;
// ^? string | undefined
});
`
By default, events will be transformed by the validation. This behavior can be modified to also transform Contexts and Responses, or turned off altogether to just allow for non-transforming validation.
You can use your validator's error formatter, or pass in your own.
`typescript
import z from "zod";
import * as v from "valibot";
middy()
.use(
standardSchemaValidator({
eventSchema: z.object(),
errorFormatter: z.prettifyError,
}),
)
.use(
standardSchemaValidator({
eventSchema: v.object({}),
errorFormatter: v.flatten,
}),
)
.handler(lamdaFunction);
``
Any and all issues and PRs are greatly appreciated.
Please leave a star if this project was helpful to you.