Skip to content

Instantly share code, notes, and snippets.

@SigurdMW
Created March 1, 2021 11:15
Show Gist options
  • Save SigurdMW/d1370d1cf0d6996249dcbd111eb1a987 to your computer and use it in GitHub Desktop.
Save SigurdMW/d1370d1cf0d6996249dcbd111eb1a987 to your computer and use it in GitHub Desktop.
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