-
Notifications
You must be signed in to change notification settings - Fork 10
/
zod-utils.ts
145 lines (125 loc) · 4.41 KB
/
zod-utils.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import * as R from 'remeda'
import * as z from 'zod'
export {z}
export function parseIf<T>(value: unknown, typeguard: (v: unknown) => v is T) {
return typeguard(value) ? value : undefined
}
export function nonNullable<T>(value: T): value is NonNullable<T> {
return value != null
}
export type JsonLiteral = z.infer<typeof zLiteral>
export const zLiteral = z.union([z.string(), z.number(), z.boolean(), z.null()])
export type Json = JsonLiteral | {[key: string]: Json} | Json[]
export const zJson: z.ZodType<Json> = z.lazy(() =>
z.union([zLiteral, z.array(zJson), z.record(zJson)]),
)
export type JsonObject = z.infer<typeof zJsonObject>
export const zJsonObject = z.record(zJson)
export function zGuard<T, U>(fn: (input: T) => U | Promise<U>) {
return (out: T, ctx: z.RefinementCtx) => {
function catchError(err: unknown) {
if (err instanceof z.ZodError) {
err.issues.forEach((issue) => ctx.addIssue({...issue, fatal: true}))
} else {
ctx.addIssue({code: 'custom', fatal: true, message: `${err}`})
}
return err as U // Due to fatal, this will never be used
}
try {
const ret = fn(out)
return R.isPromise(ret) ? ret.catch(catchError) : ret
} catch (err) {
return catchError(err)
}
}
}
export function zGuardTransform<ZType extends z.ZodTypeAny, U>(
fn: (input: z.output<ZType>) => U | Promise<U>,
) {
return (zType: ZType) => zType.transform(zGuard(fn))
}
export function zRefineNonNull<TOut, ZType extends z.ZodType<TOut>>(
zType: ZType,
) {
return zType
.superRefine((input) => !!input)
.transform((input) => input as NonNullable<TOut>)
}
/**
* e.g. `schema.transform(cast<TOut>())
* Useful as a casting typeguard
* HOC because prettier doesn't understand how to format... https://share.cleanshot.com/vfED5U
* and it is also tricky in ts to declare
*
*/
// prettier-ignore
export const cast = <T>() => (_input: unknown) => _input as T
// prettier-ignore
/** `schema.refine(castIs<TOut>)` */
export const castIs = <T>() =>(_input: unknown): _input is T => true
/** `zCast<TOut>()` standalone */
export const zCast = <T>(...args: Parameters<typeof z['unknown']>) =>
z.unknown(...args).refine(castIs<T>())
/** `castInput(schema)<TInput>()` */
export const castInput =
<T extends z.ZodTypeAny>(schema: T) =>
<TInput extends T['_input']>() =>
schema as z.ZodType<T['_output'], z.ZodTypeDef, TInput>
export function isZodType(input: unknown): input is z.ZodTypeAny {
const obj = input as z.ZodTypeAny
return typeof obj === 'object' && typeof obj._def === 'object'
}
/** Not secure because we could leak secrets to logs */
export function zodInsecureDebug() {
z.setErrorMap((_issue, ctx) => {
// Need to get the `schema` as well.. otherwise very hard to debug
// which part is failing because we use Zod for almost everything...
console.error('[zod] Data did not pass validation', {
data: ctx.data,
issue: _issue,
})
return {message: ctx.defaultError}
})
}
// MARK: - Custom wrapper and error handling
/** Better ZodParser... @see https://github.com/colinhacks/zod/issues/105 */
export function zParser<T extends z.ZodType>(schema: T) {
const _catchErr = (err: unknown) =>
catchZodError(err, {rootTypeName: schema.description})
const parseUnknown = (
...args: Parameters<typeof schema.parse>
): z.output<T> => {
try {
return schema.parse(...args)
} catch (err) {
return _catchErr(err)
}
}
const parseUnknownAsync: typeof schema.parseAsync = (
...args: Parameters<typeof schema.parseAsync>
): Promise<z.output<T>> => schema.parseAsync(...args).catch(_catchErr)
return {
schema,
_input: schema._input as z.input<T>,
_output: schema._output as z.output<T>,
parseUnknown,
parse: (
input: T['_input'],
...rest: Rest1<Parameters<typeof parseUnknown>>
) => parseUnknown(input, ...rest),
parseUnknownAsync,
parseAsync: (
input: T['_input'],
...reest: Rest1<Parameters<typeof parseUnknown>>
) => parseUnknownAsync(input, ...reest),
}
}
type Rest1<T extends [any, ...any[]]> = T extends [any, ...infer U] ? U : []
export function catchZodError(err: unknown, opts?: {rootTypeName?: string}) {
if (err instanceof z.ZodError && err.issues[0]) {
const issue = err.issues[0]
const paths = R.compact([opts?.rootTypeName, ...issue.path])
throw new Error(`${issue.code} at ${paths.join('.')}: ${issue.message}`)
}
throw err
}