Skip to content

Instantly share code, notes, and snippets.

@OmkarK45
Created November 8, 2021 13:27
Show Gist options
  • Save OmkarK45/42c43a13b170ed2bb9418f02d7f7be47 to your computer and use it in GitHub Desktop.
Save OmkarK45/42c43a13b170ed2bb9418f02d7f7be47 to your computer and use it in GitHub Desktop.
Validate Incoming Body Against a yup schema
import { NextFunction, Request, Response } from 'express'
import { BaseSchema } from 'yup'
import { MixedSchema } from 'yup/lib/mixed'
/**
* This middleware checks the req.body against an yup schema provided in it
* @example
* ```
* validate(incomingRequestBody, incomingBodySchema)
*
* ```
* @returns - If body is not valid according to yup schema, returns yup validation error.
* calls next() if incoming body adheres to schema shape.
* */
export const validate =
(schema: MixedSchema | BaseSchema) =>
async (
req: Request,
res: Response,
next: NextFunction
): Promise<void | Response> => {
const body = req.body
try {
await schema.validate(body, {
abortEarly: false,
})
return next()
} catch (error) {
return res.status(400).json({
error,
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment