Skip to content

Commit

Permalink
Sync alphalib
Browse files Browse the repository at this point in the history
  • Loading branch information
kvz committed Dec 19, 2024
1 parent a1fde6c commit 4b6d448
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/alphalib/zodParseWithContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { z } from 'zod'

type ZodIssueWithContext = z.ZodIssue & { parentObj: unknown }

function getByPath(obj: unknown, path: string): unknown {
if (!path) return obj
const parts = path.split('.')
let current = obj
for (const part of parts) {
if (current == null || typeof current !== 'object') return undefined
current = (current as Record<string, unknown>)[part]
}
return current
}

export function zodParseWithContext<T extends z.ZodType>(
schema: T,
obj: unknown,
): { success: boolean; safe?: z.infer<T>; errors: ZodIssueWithContext[] } {
const zodRes = schema.safeParse(obj)
if (!zodRes.success) {
const reportErrors: ZodIssueWithContext[] = []
for (const error of zodRes.error.errors) {
const lastPath = error.path
let parentObj: unknown = {}
if (lastPath) {
const strPath = lastPath.slice(0, -1).join('.')
parentObj = getByPath(obj, strPath) ?? {}
}

reportErrors.push({
...error,
parentObj,
})
}
return { success: false, errors: reportErrors }
}

return { success: true, safe: zodRes.data, errors: [] }
}

0 comments on commit 4b6d448

Please sign in to comment.