-
-
Notifications
You must be signed in to change notification settings - Fork 90
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
16 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,33 +1,31 @@ | ||
import { BadRequest } from "@tsed/exceptions"; | ||
import { ExtendedBadRequest } from "src/exceptions/extended-bad-request"; | ||
import { z } from "zod"; | ||
|
||
export function validateSchema<Schema extends z.ZodTypeAny>( | ||
schema: Schema, | ||
values: unknown, | ||
): z.infer<Schema> { | ||
let data = {}; | ||
const errors: Record<string, string> = {}; | ||
const data = schema.safeParse(values); | ||
|
||
try { | ||
data = schema.parse(values); | ||
} catch (error) { | ||
const zodError = error instanceof z.ZodError ? error : null; | ||
if (!data.success) { | ||
const zodError = data.error; | ||
const errors: Record<string, string> = {}; | ||
|
||
if (zodError) { | ||
const { fieldErrors } = zodError.flatten(); | ||
|
||
for (const fieldError in fieldErrors) { | ||
const [errorMessage] = fieldErrors[fieldError] ?? []; | ||
if (errorMessage) { | ||
errors[fieldError] = errorMessage; | ||
} | ||
const { fieldErrors } = zodError.flatten(); | ||
for (const fieldError in fieldErrors) { | ||
const [errorMessage] = fieldErrors[fieldError] ?? []; | ||
if (errorMessage) { | ||
errors[fieldError] = errorMessage; | ||
} | ||
} | ||
} | ||
|
||
if (Object.values(errors).length > 0) { | ||
throw new ExtendedBadRequest(errors); | ||
if (Object.values(errors).length > 0) { | ||
throw new ExtendedBadRequest(errors); | ||
} | ||
|
||
throw new BadRequest(JSON.stringify(zodError.message)); | ||
} | ||
|
||
return data as z.infer<Schema>; | ||
return data.data; | ||
} |