Initial commit
This commit is contained in:
33
api/middlewares/validate.ts
Normal file
33
api/middlewares/validate.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user