JSFiddle - React, Tailwind, and code Playground
by David Santiago
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/index.min.js"></script>
JavaScript
import { z } from "zod";
const billogramEventSchema = z.object({
callback_id: z.string(),
callback_timestamp: z.string(),
callback_type: z.literal("BillogramEvent"),
billogram: z.object({
id: z.string(),
state: z.string(),
}),
event: z.object({
type: z.literal("ReminderSent"),
event_uuid: z.string(),
}),
});
const otherEventSchema = z.object({
callback_id: z.string(),
callback_timestamp: z.string(),
callback_type: z.literal("OTHEREvent"),
});
const callbackSchema = z.object({
callback_id: z.string(),
callback_timestamp: z.string(),
callback_type: z.union([
z.literal("BillogramEvent"),
z.literal("OTHEREvent"),
]),
billogram: z.optional(billogramEventSchema),
event: z.optional(z.object({})), // Empty schema for other events
});
// Example usage with the provided objects
const object1 = {
callback_id: "9397962b-5571-464c-9a97-2801a6fc7d18",
callback_timestamp: "2023-11-21T08:00:02.466914Z",
callback_type: "BillogramEvent",
billogram: {
id: "VHwdtVxD",
state: "Reminder_2",
},
event: {
type: "ReminderSent",
event_uuid: "71216815-f426-43aa-9bda-4fcc8e05f65e",
},
};
const object2 = {
callback_id: "9397962b-5571-464c-9a97-2801a6fc7d18",
callback_timestamp: "2023-11-21T08:00:02.466914Z",
callback_type: "OTHEREvent",
};
// Validate objects against the schema
const validatedObject1 = callbackSchema.parse(object1);
const validatedObject2 = callbackSchema.parse(object2);
console.log(validatedObject1);
console.log(validatedObject2);