I want to validate data that comes from the backend, I want this data to resemble this typescript shape
export interface Booking {
locationId: string;
bookingId: number;
spotId: string;
from: string;
to: string;
status: "pending" | "confirmed" | "closed";
}
so I have written zod schema and a validator function like so:
const bookingOnLoadResponse = z.array(
z.object({
locationId: z.string(),
bookingId: z.number(),
spotId: z.string(),
status: z.literal("pending" || "confirmed" || "closed"),
from: z.string(),
to: z.string(),
})
);
export function bookingOnLoadValidator(bookingArray: unknown) {
return bookingOnLoadResponse.parse(bookingArray);
}
now I know that the problem is with the status field, as it was added recently and I see in the logs that this field is missing in the response, but from Zod all I get is:
[Unhandled promise rejection: ZodError: []
at http://10.3.42.237:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:226607:293 in _createSuperInternal
at node_modules/zod/lib/ZodError.js:29:8 in constructor
at node_modules/zod/lib/types.js:29:22 in handleResult
at node_modules/zod/lib/types.js:120:23 in ZodType#parse
at utils/zodSchemas/bookingResponseSchema.ts:16:9 in bookingOnLoadValidator
at utils/fetchFunctions.ts:28:9 in fetchBookings
is there a way to get a more detailed description of what causes the problem? Thanks
My guess is that the promise rejection is a result of parse
throwing. If it's called from within a promise's callback or from an async
function then the ultimate result would be a promise rejection.
parse
is going to throw if it fails to parse the schema you've specified. If anything about the shape of your data is different than you're expecting, then it will throw. It's hard to say exactly why it's throwing without seeing the JSON
, but my guess is that your definition for status
is not correct.
||
is going to be evaluated as a logical or expression so "pending" || "confirmed" || "closed"
resolves to "pending"
(because "pending" is truth-y and ||
will resolve to the first value in the chain that is truth-y). Because of that, the other values for status are going to result in failure to parse.
Try
status: z.enum(["pending", "confirmed", "closed"]),