tsoa-zod-validator
Version:
Zod validation decorators for tsoa
59 lines (58 loc) • 1.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodValidationError = void 0;
/**
* Custom error class for Zod validation errors
*/
class ZodValidationError extends Error {
/**
* Creates a new ZodValidationError
* @param zodError The original Zod error
* @param target The validation target
*/
constructor(zodError, target) {
super('Validation failed');
this.name = 'ZodValidationError';
this.zodError = zodError;
this.target = target;
this.errors = this.parseZodError(zodError, target);
}
/**
* Parses a Zod error into an array of ValidationErrorDetail objects
* @param zodError The Zod error to parse
* @param target The validation target
* @returns An array of ValidationErrorDetail objects
*/
parseZodError(zodError, target) {
return zodError.issues.map((error) => {
const field = error.path.length > 0 ? `${target}.${error.path.join('.')}` : target;
return {
field,
message: error.message,
code: error.code,
receivedValue: 'received' in error ? error.received : undefined,
};
});
}
/**
* Creates a simple error response
* @returns A simple error response
*/
toSimpleFormat() {
return {
error: 'Validation failed',
message: this.errors.map((e) => e.message).join(', '),
};
}
/**
* Creates a detailed error response
* @returns A detailed error response
*/
toDetailedFormat() {
return {
error: 'Validation failed',
details: this.errors,
};
}
}
exports.ZodValidationError = ZodValidationError;