| import { Request, Response, NextFunction } from 'express';
|
| import { AnyZodObject, ZodError } from 'zod';
|
| import xss from 'xss';
|
|
|
| |
| |
| |
|
|
| export const validateRequest = (schema: AnyZodObject) => {
|
| return async (req: Request, res: Response, next: NextFunction) => {
|
| try {
|
|
|
| if (req.body && typeof req.body === 'object') {
|
| for (const key of Object.keys(req.body)) {
|
| if (typeof req.body[key] === 'string') {
|
| req.body[key] = xss(req.body[key], {
|
| whiteList: {},
|
| stripIgnoreTag: true,
|
| stripIgnoreTagBody: ['script']
|
| });
|
| }
|
| }
|
| }
|
|
|
|
|
| await schema.parseAsync({
|
| body: req.body,
|
| query: req.query,
|
| params: req.params,
|
| });
|
|
|
| return next();
|
| } catch (error) {
|
| if (error instanceof ZodError) {
|
| return res.status(400).json({
|
| error: 'Validation failed',
|
| details: error.errors.map(err => ({
|
| path: err.path.join('.'),
|
| message: err.message
|
| }))
|
| });
|
| }
|
| return res.status(500).json({ error: 'Internal server error during validation' });
|
| }
|
| };
|
| };
|
|
|