Created
November 8, 2021 13:27
-
-
Save OmkarK45/42c43a13b170ed2bb9418f02d7f7be47 to your computer and use it in GitHub Desktop.
Validate Incoming Body Against a yup schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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