-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathocpi.utils.ts
More file actions
43 lines (41 loc) · 1.21 KB
/
ocpi.utils.ts
File metadata and controls
43 lines (41 loc) · 1.21 KB
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
import {
ZodArray,
ZodNullable,
ZodObject,
ZodOptional,
ZodTuple,
ZodTypeAny,
} from "zod";
/**
* Custom deepPartial implementation for OCPI
* Based on https://github.com/colinhacks/zod/blob/f455e3284f7a5cbe11259477073b15256b946133/src/types.ts#L1421
*
* All properties are made optional AND nullable
*/
export const ocpiDeepPartial = (schema: ZodTypeAny): any => {
if (schema instanceof ZodObject) {
const newShape: any = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(
ocpiDeepPartial(fieldSchema),
).nullable();
}
return new ZodObject({
...schema._def,
shape: () => newShape,
}) as any;
} else if (schema instanceof ZodArray) {
return ZodArray.create(ocpiDeepPartial(schema.element));
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(ocpiDeepPartial(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(ocpiDeepPartial(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(
schema.items.map((item: any) => ocpiDeepPartial(item)),
);
} else {
return schema;
}
};