Created
May 30, 2024 05:54
-
-
Save SwapnilSoni1999/21cbfe674c383b37d54820d0aaca8229 to your computer and use it in GitHub Desktop.
Universal zod validator for express.js
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 { AnyZodObject, ZodTypeAny } from 'zod' | |
import { | |
NextFunction, | |
Request, | |
RequestHandler, | |
Response | |
} from 'express' | |
import { HttpError } from '@/lib/errors.lib' | |
type RequestPayloadIn = 'body' | 'query' | 'params' | |
const validator = | |
( | |
args: Partial< | |
Record<RequestPayloadIn, AnyZodObject | ZodTypeAny> | |
> | |
): RequestHandler => | |
async ( | |
req: Request, | |
res: Response, | |
next: NextFunction | |
): Promise<void> => { | |
try { | |
const keys = Object.keys(args) as RequestPayloadIn[] | |
for (const key of keys) { | |
const payload = req[key] | |
console.log(payload) | |
const validator = args[key] | |
if (validator) { | |
const result = validator.safeParse(payload) | |
if (!result.success) { | |
console.log(result.error.flatten()) | |
next( | |
new HttpError({ | |
statusCode: 422, | |
message: 'Unprocessable Entity Error', | |
errors: result.error.errors | |
}) | |
) | |
return | |
} | |
if (result.data) { | |
req[key] = result.data | |
} | |
} | |
} | |
next() | |
} catch (err) { | |
next( | |
new HttpError({ | |
statusCode: 500, | |
message: | |
(err as Error).stack ?? (err as Error).message | |
}) | |
) | |
} | |
} | |
export default validator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment