@castore/command-zod
TypeScript icon, indicating that this package has built-in type declarations

2.3.1 • Public • Published

Zod Command

DRY Castore Command definition using zod.

📥 Installation

# npm
npm install @castore/command-zod

# yarn
yarn add @castore/command-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

👩‍💻 Usage

import z from 'zod';

import { ZodCommand } from '@castore/command-zod';
import { tuple } from '@castore/core';

const pokemonAppearedInputSchema = z.object({
  name: z.string(),
  level: z.number(),
});

const pokemonAppearedOutputSchema = z.object({
  pokemonId: z.string().uuid(),
});

// 👇 generics are correctly inferred
const pokemonAppearCommand = new ZodCommand({
  commandId: 'POKEMON_APPEAR',
  requiredEventStores: tuple(pokemonsEventStore),
  inputSchema: pokemonAppearedInputSchema,
  outputSchema: pokemonAppearedOutputSchema,
  // 👇 handler input/output types are correctly inferred
  handler: async (
    commandInput,
    [pokemonsEventStore],
    { generateUuid }: { generateUuid: () => string },
  ) => {
    const { name, level } = commandInput;
    const pokemonId = generateUuid();

    await pokemonsEventStore.pushEvent({
      aggregateId: pokemonId,
      version: 1,
      type: 'POKEMON_APPEARED',
      payload: { name, level },
    });

    return { pokemonId };
  },
});

👇 Equivalent to:

import { Command } from '@castore/core';

type RequiredEventStores = [typeof pokemonsEventStore];
type CommandInput = { name: string; level: number };
type CommandOutput = { pokemonId: string };

const pokemonAppearCommand = new Command<
  RequiredEventStores,
  RequiredEventStores,
  CommandInput,
  CommandOutput
>({
  commandId: 'POKEMON_APPEAR',
  requiredEventStores: [pokemonsEventStore],
  handler: async (commandInput, [pokemonsEventStore]) => {
    // ...same code
  },
});

⚙️ Properties & Methods

ZodCommand implements the Command class and adds the following properties to it:

  • inputSchema (?object): The command input zod schema
const inputSchema = pokemonAppearCommand.inputSchema;
// => pokemonAppearedInputSchema
  • outputSchema (?object): The command output zod schema
const outputSchema = pokemonAppearCommand.outputSchema;
// => pokemonAppearedOutputSchema

Package Sidebar

Install

npm i @castore/command-zod

Weekly Downloads

252

Version

2.3.1

License

MIT

Unpacked Size

108 kB

Total Files

21

Last publish

Collaborators

  • thomasaribart
  • valentinbeggi
  • charlesgery
  • julietteff