-
Notifications
You must be signed in to change notification settings - Fork 1
/
zod-proxy.ts
50 lines (44 loc) · 1.13 KB
/
zod-proxy.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
// deno-lint-ignore-file no-explicit-any
export function zodProxy(z: any, props: any) {
const proxy = new Proxy(z, {
get(target, prop) {
let original = target[prop];
if (
typeof original === "function" &&
typeof prop === "string" &&
lowercaseLetters.indexOf(prop[0]) !== -1 &&
!original._isProxy &&
ignoreProperties.indexOf(prop) === -1
) {
original = original.bind(proxy);
return (...args: any[]) => {
const result = original(...args);
if (
result &&
typeof result === "object" &&
typeof result.constructor === "function" &&
result.constructor.name.startsWith("Zod") &&
!result._isProxy
) {
return zodProxy(
Object.assign(result, props),
props,
);
}
return result;
};
}
return original;
},
});
return proxy;
}
const lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
const ignoreProperties = [
"bind",
"parse",
"parseAsync",
"safeParse",
"safeParseAsync",
"then",
];