Files
defiQUG e8ae376e90 Enhance API services with validation and error handling improvements
- Integrated Zod validation schemas across various API routes to ensure input integrity and improve error handling.
- Updated `mapping-service`, `orchestrator`, `packet-service`, and `webhook-service` to utilize validation middleware for request parameters and bodies.
- Improved error handling in webhook management, packet generation, and compliance routes to provide clearer feedback on request failures.
- Added new validation schemas for various endpoints, enhancing overall API robustness and maintainability.
- Updated dependencies in `package.json` to include the new validation library.
2025-12-12 20:23:45 -08:00

78 lines
1.7 KiB
TypeScript

/**
* Express validation middleware using Zod
* Validates request body, query parameters, and path parameters
*/
import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError } from 'zod';
export interface ValidationOptions {
body?: ZodSchema;
query?: ZodSchema;
params?: ZodSchema;
}
/**
* Create validation middleware for Express routes
*/
export function validate(options: ValidationOptions) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
// Validate request body
if (options.body) {
req.body = options.body.parse(req.body);
}
// Validate query parameters
if (options.query) {
req.query = options.query.parse(req.query);
}
// Validate path parameters
if (options.params) {
req.params = options.params.parse(req.params);
}
next();
} catch (error) {
if (error instanceof ZodError) {
const validationErrors = error.errors.map((err) => ({
path: err.path.join('.'),
message: err.message,
code: err.code,
}));
return res.status(400).json({
code: 'VALIDATION_ERROR',
message: 'Request validation failed',
errors: validationErrors,
});
}
next(error);
}
};
}
/**
* Validate request body only
*/
export function validateBody(schema: ZodSchema) {
return validate({ body: schema });
}
/**
* Validate query parameters only
*/
export function validateQuery(schema: ZodSchema) {
return validate({ query: schema });
}
/**
* Validate path parameters only
*/
export function validateParams(schema: ZodSchema) {
return validate({ params: schema });
}