Source

middlewares/validateRequest.js

/**
 * Request validation middleware
 * Uses Zod for schema validation
 */
import { getLogger } from "@utils/asyncLocalStorage";
import { ZodError } from "zod";
/**
 * Middleware factory for request validation
 * @category Middlewares
 * @param {object} schema The schema to validate the request
 * @param {ZodSchema<unknown>} schema.body The schema to validate the request body
 * @param {ZodSchema<unknown>} schema.query The schema to validate the request query
 * @param {ZodSchema<Record<string, string>>} schema.params The schema to validate the request parameters
 * @returns {Function} Express middleware function
 */
export function validateRequest(schema) {
    return (req, res, next) => {
        const logger = getLogger();
        try {
            // Validate request body
            if (schema.body) {
                req.body = schema.body.parse(req.body);
            }
            // Validate query parameters
            if (schema.query) {
                const validatedQuery = schema.query.parse(req.query);
                // Replace the query object with validated data
                Object.assign(req.query, validatedQuery);
            }
            // Validate request parameters
            if (schema.params) {
                req.params = schema.params.parse(req.params);
            }
            next();
        }
        catch (error) {
            if (error instanceof ZodError) {
                logger.warn({
                    validationErrors: error.errors,
                    url: req.url,
                    method: req.method,
                }, "Request validation failed");
                res.status(400).json({
                    success: false,
                    error: {
                        message: "Validation failed",
                        details: error.errors,
                    },
                });
                return;
            }
            next(error);
        }
    };
}