I want to be able to
- create and send a Zod instance as a serialized JSON.
- receive such a JSON and parse it back to a Zod instance.
Problem: On the receiving part using Zod Schema parse
throws error
ZodError: [
{
"code": "invalid_type",
"expected": "string",
"received": "object",
"path": [
0,
"parents",
0
],
"message": "Expected string, received object"
},
Workaround:
Sending part:
Remap all references as Zod expects those to be list of string ids instead of objects.
export async function GET() {
const dbPersons = await getCollection("person");
const persons = dbPersons.map((dbPerson) => {
// Only this line causes the error above
return dbPerson.data;
// Workaround which works
const parents = dbPerson.data.parents?.map(parent => parent.id);
const children = dbPerson.data.children?.map(child => child.id);
const spouses = dbPerson.data.spouses?.map(spouse => spouse.id);
return Object.assign({}, {
...dbPerson.data,
parents,
children,
spouses
});
});
return new Response(JSON.stringify(persons));
}
Receiving part:
const personAPIResp = await personsApi.json();
const persons = await ZPersonArray.parseAsync(personAPIResp);
Affected part of the schema:
export const ZPerson = z.object({
id: z.number({
message: "Unique identifier of a person"
}),
// ...
// Parents
parents: z.array(reference("person")).optional(),
// ...
});
Is there a better solution like a different parser or a different way to serialize?