Skip to content

Commit 4b6d448

Browse files
committed
Sync alphalib
1 parent a1fde6c commit 4b6d448

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import type { z } from 'zod'
2+
3+
type ZodIssueWithContext = z.ZodIssue & { parentObj: unknown }
4+
5+
function getByPath(obj: unknown, path: string): unknown {
6+
if (!path) return obj
7+
const parts = path.split('.')
8+
let current = obj
9+
for (const part of parts) {
10+
if (current == null || typeof current !== 'object') return undefined
11+
current = (current as Record<string, unknown>)[part]
12+
}
13+
return current
14+
}
15+
16+
export function zodParseWithContext<T extends z.ZodType>(
17+
schema: T,
18+
obj: unknown,
19+
): { success: boolean; safe?: z.infer<T>; errors: ZodIssueWithContext[] } {
20+
const zodRes = schema.safeParse(obj)
21+
if (!zodRes.success) {
22+
const reportErrors: ZodIssueWithContext[] = []
23+
for (const error of zodRes.error.errors) {
24+
const lastPath = error.path
25+
let parentObj: unknown = {}
26+
if (lastPath) {
27+
const strPath = lastPath.slice(0, -1).join('.')
28+
parentObj = getByPath(obj, strPath) ?? {}
29+
}
30+
31+
reportErrors.push({
32+
...error,
33+
parentObj,
34+
})
35+
}
36+
return { success: false, errors: reportErrors }
37+
}
38+
39+
return { success: true, safe: zodRes.data, errors: [] }
40+
}

0 commit comments

Comments
 (0)