DRY Castore EventType
definition using zod
.
# npm
npm install @castore/event-type-zod
# yarn
yarn add @castore/event-type-zod
This package has @castore/core
and zod
(above v3) as peer dependencies, so you will have to install them as well:
# npm
npm install @castore/core zod
# yarn
yarn add @castore/core zod
import z from 'zod';
import { ZodEventType } from '@castore/event-type-zod';
const pokemonAppearedPayloadSchema = z.object({
name: z.string(),
level: z.number(),
});
const pokemonAppearedMetadataSchema = z.object({
trigger: z.enum(['random', 'scripted']).optional(),
});
// 👇 generics are correctly inferred
const pokemonAppearedEventType = new ZodEventType({
type: 'POKEMON_APPEARED',
payloadSchema: pokemonAppearedPayloadSchema,
metadataSchema: pokemonAppearedMetadataSchema,
});
👇 Equivalent to:
import { EventType } from '@castore/core';
const pokemonAppearedEventType = new EventType<
'POKEMON_APPEARED',
{ name: string; level: number },
{ trigger?: 'random' | 'scripted' }
>({ type: 'POKEMON_APPEARED' });
ZodEventType
implements the EventType
class and adds the following properties to it:
-
payloadSchema (?object)
: The event type payload zod schema
const payloadSchema = pokemonAppearedEventType.payloadSchema;
// => pokemonAppearedPayloadSchema
-
metadataSchema (?object)
: The event type metadata zod schema
const metadataSchema = pokemonAppearedEventType.metadataSchema;
// => pokemonAppearedMetadataSchema