Spaces:
Sleeping
Sleeping
| import { Request, Response, NextFunction } from 'express'; | |
| import { AnyZodObject, ZodError } from 'zod'; | |
| export const validate = (schema: AnyZodObject) => { | |
| return async (req: Request, res: Response, next: NextFunction) => { | |
| try { | |
| const parsed = await schema.parseAsync({ | |
| body: req.body, | |
| query: req.query, | |
| params: req.params, | |
| }); | |
| if (parsed.body !== undefined) req.body = parsed.body; | |
| if (parsed.query !== undefined) req.query = parsed.query; | |
| if (parsed.params !== undefined) req.params = parsed.params; | |
| return next(); | |
| } catch (error) { | |
| if (error instanceof ZodError) { | |
| return res.status(400).json({ | |
| sukses: false, | |
| pesan: 'Validasi input gagal', | |
| errors: error.errors.map((err) => ({ | |
| field: err.path.slice(1).join('.'), | |
| message: err.message, | |
| })), | |
| }); | |
| } | |
| return next(error); | |
| } | |
| }; | |
| }; | |