File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments