-
Notifications
You must be signed in to change notification settings - Fork 0
/
shapeInfo.ts
85 lines (74 loc) · 1.55 KB
/
shapeInfo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { ZodTypeAny } from 'zod'
type ZodTypeName =
| 'ZodString'
| 'ZodNumber'
| 'ZodBoolean'
| 'ZodDate'
| 'ZodEnum'
type ShapeInfo = {
typeName: ZodTypeName | null
optional: boolean
nullable: boolean
getDefaultValue?: () => unknown
enumValues?: string[]
}
function shapeInfo(
shape?: ZodTypeAny,
optional = false,
nullable = false,
getDefaultValue?: ShapeInfo['getDefaultValue'],
enumValues?: ShapeInfo['enumValues'],
): ShapeInfo {
if (!shape) {
return { typeName: null, optional, nullable, getDefaultValue, enumValues }
}
const typeName = shape._def.typeName
if (typeName === 'ZodEffects') {
return shapeInfo(
shape._def.schema,
optional,
nullable,
getDefaultValue,
enumValues,
)
}
if (typeName === 'ZodOptional') {
return shapeInfo(
shape._def.innerType,
true,
nullable,
getDefaultValue,
enumValues,
)
}
if (typeName === 'ZodNullable') {
return shapeInfo(
shape._def.innerType,
optional,
true,
getDefaultValue,
enumValues,
)
}
if (typeName === 'ZodDefault') {
return shapeInfo(
shape._def.innerType,
optional,
nullable,
shape._def.defaultValue,
enumValues,
)
}
if (typeName === 'ZodEnum') {
return {
typeName,
optional,
nullable,
getDefaultValue,
enumValues: shape._def.values,
}
}
return { typeName, optional, nullable, getDefaultValue, enumValues }
}
export { shapeInfo }
export type { ZodTypeName, ShapeInfo }