34 lines
963 B
TypeScript
34 lines
963 B
TypeScript
import type { Request, Response, NextFunction } from 'express'
|
|
import { ZodSchema, ZodError } from 'zod'
|
|
import { ValidationError } from '../../shared/errors/index.js'
|
|
|
|
export const validateBody = (schema: ZodSchema) => {
|
|
return (req: Request, _res: Response, next: NextFunction) => {
|
|
try {
|
|
req.body = schema.parse(req.body)
|
|
next()
|
|
} catch (error) {
|
|
if (error instanceof ZodError) {
|
|
next(new ValidationError('Request validation failed', { issues: error.issues }))
|
|
} else {
|
|
next(error)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export const validateQuery = (schema: ZodSchema) => {
|
|
return (req: Request, _res: Response, next: NextFunction) => {
|
|
try {
|
|
req.query = schema.parse(req.query) as typeof req.query
|
|
next()
|
|
} catch (error) {
|
|
if (error instanceof ZodError) {
|
|
next(new ValidationError('Query validation failed', { issues: error.issues }))
|
|
} else {
|
|
next(error)
|
|
}
|
|
}
|
|
}
|
|
}
|