-
Notifications
You must be signed in to change notification settings - Fork 0
/
zod-to-invalid-parameters.ts
52 lines (42 loc) · 1.21 KB
/
zod-to-invalid-parameters.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
import { isArray, isBoolean, isNull, isNumber, isObject, isString } from '@chubbyts/chubbyts-decode-encode/dist';
import { ZodError } from 'zod';
type InvalidParameter = {
name: string;
reason: string;
[key: string]: unknown;
};
const resolveName = (path: Array<number | string>): string => {
return path
.map((pathPart, i) => {
return i > 0 ? `[${pathPart}]` : pathPart;
})
.join('');
};
const filterContext = (rest: unknown): unknown => {
if (isObject(rest)) {
return Object.fromEntries(Object.entries(rest).map(([key, value]) => [key, filterContext(value)]));
}
if (isArray(rest)) {
return rest.map(filterContext);
}
if (isNull(rest) || isBoolean(rest) || isNumber(rest) || isString(rest)) {
return rest;
}
if (rest instanceof ZodError) {
return zodToInvalidParameters(rest);
}
if (rest instanceof Date) {
return rest.toJSON();
}
return '**filtered**';
};
export const zodToInvalidParameters = (zodError: ZodError): Array<InvalidParameter> => {
return zodError.errors.map((error) => {
const { path, message, ...context } = error;
return {
name: resolveName(path),
reason: message,
context: filterContext(context),
};
});
};