WorkshopTasker/server/utils/validation.ts

32 lines
924 B
TypeScript
Raw Permalink Normal View History

import { createError } from "#imports";
2023-05-24 09:40:45 +02:00
export function createValidationError(errors: Map<string, string>) {
let message = "Invalid parameters: ";
for (const i in errors)
message += i + ", ";
message = message.slice(0, -2);
return createError({
statusCode: 400,
message,
data: {
errors: Object.fromEntries(errors),
},
});
}
export function handleRecursedValidationError(e: unknown, errors: Map<string, string>, element: string) {
if (typeof e !== "object") throw e;
if (!e) throw e;
if (!(e as any).data || !(e as any).message) throw e;
const upstreamErrors = (e as any).data.errors as any;
const upstreamMessage = (e as any).message;
if (upstreamErrors) {
for (const j in upstreamErrors)
errors.set(`${element}.${j}`, String(upstreamErrors[j]));
} else if (upstreamMessage) {
errors.set(`${element}`, String(upstreamMessage));
} else {
throw e;
}
}