directus-task-management/dist/api/middleware/validation.middleware.js

120 lines
4.1 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateMultiple = exports.validate = void 0;
const zod_1 = require("zod");
/**
* Validation middleware factory
* Creates middleware that validates request data against a Zod schema
*/
const validate = (schema, source = 'body') => {
return async (req, res, next) => {
try {
// Validate the specified part of the request
const data = await schema.parseAsync(req[source]);
// Replace the request data with the parsed and validated data
req[source] = data;
next();
}
catch (error) {
if (error instanceof zod_1.ZodError) {
// Format Zod validation errors
const formattedErrors = error.issues.map(err => ({
field: err.path.join('.'),
message: err.message,
code: err.code
}));
res.status(400).json({
success: false,
error: 'Validation failed',
details: formattedErrors
});
return;
}
// Handle unexpected errors
res.status(500).json({
success: false,
error: 'Internal server error during validation'
});
return;
}
};
};
exports.validate = validate;
/**
* Validate multiple sources in a single middleware
*/
const validateMultiple = (schemas) => {
return async (req, res, next) => {
const errors = [];
try {
// Validate body if schema provided
if (schemas.body) {
try {
req.body = await schemas.body.parseAsync(req.body);
}
catch (error) {
if (error instanceof zod_1.ZodError) {
errors.push(...error.issues.map(err => ({
source: 'body',
field: err.path.join('.'),
message: err.message,
code: err.code
})));
}
}
}
// Validate query if schema provided
if (schemas.query) {
try {
req.query = await schemas.query.parseAsync(req.query);
}
catch (error) {
if (error instanceof zod_1.ZodError) {
errors.push(...error.issues.map(err => ({
source: 'query',
field: err.path.join('.'),
message: err.message,
code: err.code
})));
}
}
}
// Validate params if schema provided
if (schemas.params) {
try {
req.params = await schemas.params.parseAsync(req.params);
}
catch (error) {
if (error instanceof zod_1.ZodError) {
errors.push(...error.issues.map(err => ({
source: 'params',
field: err.path.join('.'),
message: err.message,
code: err.code
})));
}
}
}
// If there are any errors, return them
if (errors.length > 0) {
res.status(400).json({
success: false,
error: 'Validation failed',
details: errors
});
return;
}
next();
}
catch (error) {
// Handle unexpected errors
res.status(500).json({
success: false,
error: 'Internal server error during validation'
});
return;
}
};
};
exports.validateMultiple = validateMultiple;
//# sourceMappingURL=validation.middleware.js.map