Created
March 1, 2021 11:15
-
-
Save SigurdMW/d1370d1cf0d6996249dcbd111eb1a987 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import merge from "lodash/merge" | |
import * as z from "zod" | |
const recursiveError = (arr: Array<string | number>, lastError: string[] | object): any => { | |
if (!arr || arr.length === 0) { | |
return lastError | |
} | |
const [currPath, ...iss] = arr | |
let newErr | |
if (typeof currPath === "string") { | |
newErr = { [currPath]: lastError } | |
} else { | |
const newArr = new Array() | |
newArr[currPath] = lastError | |
newErr = newArr | |
} | |
return recursiveError(iss, newErr) | |
} | |
const makeStructure = (issue: z.ZodIssue) => { | |
if (issue.path.length === 1) { | |
return { [issue.path[0]]: issue.message } | |
} | |
const [deepestPath, ...rest] = [...issue.path].reverse() | |
if (typeof deepestPath === "string") { | |
return recursiveError(rest, { [deepestPath]: issue.message }) | |
} else { | |
const arr = [] | |
arr[deepestPath] = issue.message | |
return recursiveError(rest, arr) | |
} | |
} | |
export const parseSchema = <T>(values: T, schema: z.Schema<T>) => { | |
const result = schema.safeParse(values) | |
if (result.success) { | |
return {} | |
} | |
const testErrors = result.error.errors.reduce<{[key in keyof T]?: string}>((tot, e) => { | |
const structire = makeStructure(e) | |
return merge(tot, structire) | |
}, {}) | |
return testErrors | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment