-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathschemas.ts
86 lines (79 loc) · 1.98 KB
/
schemas.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
/*
* Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
*/
import {
output,
ZodEffects,
ZodError,
ZodObject,
ZodRawShape,
ZodTypeAny,
} from "zod";
import { SDKValidationError } from "../sdk/models/errors/sdkvalidationerror.js";
import { ERR, OK, Result } from "../sdk/types/fp.js";
/**
* Utility function that executes some code which may throw a ZodError. It
* intercepts this error and converts it to an SDKValidationError so as to not
* leak Zod implementation details to user code.
*/
export function parse<Inp, Out>(
rawValue: Inp,
fn: (value: Inp) => Out,
errorMessage: string,
): Out {
try {
return fn(rawValue);
} catch (err) {
if (err instanceof ZodError) {
throw new SDKValidationError(errorMessage, err, rawValue);
}
throw err;
}
}
/**
* Utility function that executes some code which may result in a ZodError. It
* intercepts this error and converts it to an SDKValidationError so as to not
* leak Zod implementation details to user code.
*/
export function safeParse<Inp, Out>(
rawValue: Inp,
fn: (value: Inp) => Out,
errorMessage: string,
): Result<Out, SDKValidationError> {
try {
return OK(fn(rawValue));
} catch (err) {
return ERR(new SDKValidationError(errorMessage, err, rawValue));
}
}
export function collectExtraKeys<
Shape extends ZodRawShape,
Catchall extends ZodTypeAny,
K extends string,
>(
obj: ZodObject<Shape, "strip", Catchall>,
extrasKey: K,
): ZodEffects<
typeof obj,
& output<ZodObject<Shape, "strict">>
& {
[k in K]: Record<string, output<Catchall>>;
}
> {
return obj.transform((val) => {
const extras: Record<string, output<Catchall>> = {};
const { shape } = obj;
for (const [key] of Object.entries(val)) {
if (key in shape) {
continue;
}
const v = val[key];
if (typeof v === "undefined") {
continue;
}
extras[key] = v;
delete val[key];
}
return { ...val, [extrasKey]: extras };
});
}