I want to have a custom middy middleware which parses the event.body with zod and saves it already typed to the request so that it can be used in the handler.
This is what I have so far:
export interface TypedAPIGatewayProxyEvent<T extends ZodType> extends APIGatewayProxyEvent {
middy: {
event: {
typedBody: z.infer<T>;
};
};
}
export const parseBody = <T extends ZodType>(
schema: T
): middy.MiddlewareObj<TypedAPIGatewayProxyEvent<z.infer<T>>, APIGatewayProxyResult> => {
const before: middy.MiddlewareFn<TypedAPIGatewayProxyEvent<z.infer< T>>, APIGatewayProxyResult> = async (request): Promise<void> => {
const typedBody = schema.parse(request.event.body);
request.event.middy = Object.assign({}, request.event.middy, {
event: Object.assign({}, request.event.middy?.event, {
typedBody: typedBody
})
});
};
return {
before
};
};
However whenever I want to use it in the handler like this:
const schema = object({
email: string(),
password: string(),
});
export type schemaType = TypeOf<typeof schema>;
export const handler = async (input: TypedAPIGatewayProxyEvent<typeof schema>): Promise<APIGatewayProxyResult> => {
const lala:schemaType = input.middy.event.typedBody;
return {
statusCode: 200,
body: JSON.stringify({
email: lala.email,
password: lala.password
})
};
};
export const lala = middy(handler)
.use(jsonBodyParser())
.use(parseBody<schemaType>(schema)); // Typescript Error
I get the following error:
TS2344: Type '{ email: string; password: string; }' does not satisfy the constraint 'ZodType<any, ZodTypeDef, any>'. Type '{ email: string; password: string; }' is missing the following properties from type 'ZodType<any, ZodTypeDef, any>': _type, _output, _input, _def, and 29 more.