Spaces:
Runtime error
Runtime error
File size: 1,253 Bytes
43a2bcc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import { createShortInput, CreateShortInput } from "../types/shorts";
import { logger } from "../logger";
import { ZodError } from "zod";
export interface ValidationErrorResult {
message: string;
missingFields: Record<string, string>;
}
export function validateCreateShortInput(input: object): CreateShortInput {
const validated = createShortInput.safeParse(input);
logger.info({ validated }, "Validated input");
if (validated.success) {
return validated.data;
}
// Process the validation errors
const errorResult = formatZodError(validated.error);
throw new Error(
JSON.stringify({
message: errorResult.message,
missingFields: errorResult.missingFields,
}),
);
}
function formatZodError(error: ZodError): ValidationErrorResult {
const missingFields: Record<string, string> = {};
// Extract all the errors into a human-readable format
error.errors.forEach((err) => {
const path = err.path.join(".");
missingFields[path] = err.message;
});
// Create a human-readable message
const errorPaths = Object.keys(missingFields);
let message = `Validation failed for ${errorPaths.length} field(s): `;
message += errorPaths.join(", ");
return {
message,
missingFields,
};
}
|