|
1 | 1 | import type { ValidationIssue } from "@typeschema/core";
|
2 | 2 | import type { Schema } from "@typeschema/main";
|
3 |
| -import type { ErrorList, ValidationErrors } from "./validation-errors.types"; |
| 3 | +import type { |
| 4 | + ErrorList, |
| 5 | + FlattenedValidationErrors, |
| 6 | + ValidationErrors, |
| 7 | +} from "./validation-errors.types"; |
4 | 8 |
|
5 | 9 | // This function is used internally to build the validation errors object from a list of validation issues.
|
6 | 10 | export const buildValidationErrors = <const S extends Schema>(issues: ValidationIssue[]) => {
|
@@ -69,3 +73,36 @@ export function returnValidationErrors<S extends Schema>(
|
69 | 73 | ): never {
|
70 | 74 | throw new ServerValidationError<S>(validationErrors);
|
71 | 75 | }
|
| 76 | + |
| 77 | +/** |
| 78 | + * Transform default formatted validation errors into flattened structure. |
| 79 | + * `rootErrors` contains global errors, and `fieldErrors` contains errors for each field, |
| 80 | + * one level deep. It skips errors for nested fields. |
| 81 | + * @param {ValidationErrors} [validationErrors] Validation errors object |
| 82 | + * @returns {FlattenedValidationErrors} Flattened validation errors |
| 83 | + */ |
| 84 | +export function flattenValidationErrors< |
| 85 | + const S extends Schema, |
| 86 | + const VE extends ValidationErrors<S>, |
| 87 | +>(validationErrors?: VE) { |
| 88 | + const flattened: FlattenedValidationErrors<S, VE> = { |
| 89 | + rootErrors: [], |
| 90 | + fieldErrors: {}, |
| 91 | + }; |
| 92 | + |
| 93 | + if (!validationErrors) { |
| 94 | + return flattened; |
| 95 | + } |
| 96 | + |
| 97 | + for (const [key, value] of Object.entries<string[] | { _errors: string[] }>(validationErrors)) { |
| 98 | + if (key === "_errors" && Array.isArray(value)) { |
| 99 | + flattened.rootErrors = [...value]; |
| 100 | + } else { |
| 101 | + if ("_errors" in value) { |
| 102 | + flattened.fieldErrors[key as keyof Omit<VE, "_errors">] = [...value._errors]; |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + return flattened; |
| 108 | +} |
0 commit comments