npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@raphaabreu/nestjs-zod-cqrs

v2.0.0

Published

Zod-validated commands, queries, events, and CloudEvents for @nestjs/cqrs

Readme

@raphaabreu/nestjs-zod-cqrs

Zod-validated commands, queries, events, and CloudEvents for @nestjs/cqrs. Define messages as classes with built-in runtime validation. Constructors accept the pre-parse input shape, instances expose the validated and transformed fields, and command/query output schemas govern handler results.

Installation

npm install @raphaabreu/nestjs-zod-cqrs

Runtime: Node.js 20 or newer.

Peer dependencies: zod >= 3.25.0 is required. @nestjs/cqrs >= 11.0.0 is required only by the command and query entry points. CI verifies both Zod 3 and Zod 4.

Entry points

import { defineZodCommand } from '@raphaabreu/nestjs-zod-cqrs/commands';
import { defineZodQuery } from '@raphaabreu/nestjs-zod-cqrs/queries';
import { defineZodEvent, defineZodCloudEvent } from '@raphaabreu/nestjs-zod-cqrs/events';

The events entry point depends only on Zod, so shared contracts and browser bundles do not load NestJS. The package root re-exports every API for NestJS applications that prefer one aggregate import.

Migrating from v1

  • Constructors accept z.input<InputSchema> and expose the schema's validated z.output<InputSchema> fields.
  • safeCreate() is safeParseInput().
  • output() is parseOutput().
  • safeOutput() is safeParseOutput().
  • The Infer alias is removed; use Zod's explicit z.input<Schema> or z.output<Schema> types.

Usage

Commands

import { z } from 'zod';
import { defineZodCommand } from '@raphaabreu/nestjs-zod-cqrs/commands';

class PlaceOrderCommand extends defineZodCommand({
  input: z.object({
    productId: z.string(),
    quantity: z.number().int().positive(),
  }),
  output: z.object({
    orderId: z.string(),
    createdAt: z.string().datetime(),
  }),
}) {}

// Validated construction — throws on invalid input
const cmd = new PlaceOrderCommand({ productId: 'p1', quantity: 3 });

// Shape handler return value — validates and strips extra fields (throws on failure)
const output = PlaceOrderCommand.parseOutput({
  orderId: 'o1',
  createdAt: '2024-01-01T00:00:00Z',
  ...internalFields,
});

// Safe variant — returns SafeParseResult instead of throwing
const outputResult = PlaceOrderCommand.safeParseOutput({
  orderId: 'o1',
  createdAt: '2024-01-01T00:00:00Z',
  ...internalFields,
});
if (outputResult.success) {
  console.log(outputResult.data.orderId);
}

When an input schema transforms a field, the constructor accepts its pre-parse type and the command or query exposes its parsed type:

const ListOrdersInput = z.object({
  limit: z.string().transform(Number),
});

class ListOrdersQuery extends defineZodQuery({
  input: ListOrdersInput,
  output: z.array(z.string()),
}) {}

const query = new ListOrdersQuery({ limit: '25' }); // accepted by the input schema
query.limit; // number after parsing

Events

import { z } from 'zod';
import { defineZodEvent } from '@raphaabreu/nestjs-zod-cqrs/events';

class OrderPlacedEvent extends defineZodEvent(
  z.object({
    orderId: z.string(),
    amount: z.number().positive(),
  }),
) {}

// Validated construction — throws on invalid input
const event = new OrderPlacedEvent({ orderId: 'abc', amount: 42 });

// Safe construction — returns SafeParseResult
const result = OrderPlacedEvent.safeParseInput({ orderId: 'abc', amount: 42 });
if (result.success) {
  console.log(result.data.orderId);
}

CloudEvents

defineZodCloudEvent creates a real event class whose constructor accepts only producer-owned input. new supplies the CloudEvents 1.0 envelope defaults and validates the rich model through the declared data schema. Ordinary z.object() schemas recursively strip undeclared properties. parseEnvelope and safeParseEnvelope validate complete incoming envelopes.

import { z } from 'zod';
import { defineZodCloudEvent } from '@raphaabreu/nestjs-zod-cqrs/events';

const OrderPlacedData = z
  .object({
    orderId: z.string(),
    amount: z.number().positive(),
  })
  .strip();

class OrderPlacedCloudEvent extends defineZodCloudEvent({
  type: 'com.example.order.placed',
  source: 'com.example.orders',
  dataschema: 'https://schemas.example.com/order-placed/v1',
  subjectStartsWith: 'order/',
  dataSchema: OrderPlacedData,
}) {}

const storedOrder = {
  orderId: 'o1',
  amount: 42,
  internalVersion: 7,
};

const event = new OrderPlacedCloudEvent({
  subject: `order/${storedOrder.orderId}`,
  data: storedOrder,
});

event.data; // { orderId: string; amount: number }; internalVersion was projected away

const received = OrderPlacedCloudEvent.parseEnvelope(JSON.parse(JSON.stringify(event)));
received instanceof OrderPlacedCloudEvent; // true

The @raphaabreu/nestjs-zod-cqrs/events subpath contains only event helpers and Zod. It does not load @nestjs/cqrs, which makes it suitable for shared event-contract packages.

Queries

import { z } from 'zod';
import { defineZodQuery } from '@raphaabreu/nestjs-zod-cqrs/queries';

class GetOrderQuery extends defineZodQuery({
  input: z.object({
    orderId: z.string(),
  }),
  output: z.object({
    orderId: z.string(),
    status: z.enum(['pending', 'shipped', 'delivered']),
  }),
}) {}

const query = new GetOrderQuery({ orderId: 'abc' });

// Shape handler return value — validates and strips extra fields
const output = GetOrderQuery.parseOutput({
  orderId: 'abc',
  status: 'shipped',
  ...internalFields,
});

Real-world example

Definitions

// place-order.command.ts
import { z } from 'zod';
import { defineZodCommand } from '@raphaabreu/nestjs-zod-cqrs/commands';

export class PlaceOrderCommand extends defineZodCommand({
  input: z.object({
    productId: z.string(),
    quantity: z.number().int().positive(),
  }),
  output: z.object({
    orderId: z.string(),
    createdAt: z.string().datetime(),
  }),
}) {}

export type PlaceOrderInput = z.input<typeof PlaceOrderCommand.InputSchema>;
// order-placed.event.ts
import { z } from 'zod';
import { defineZodEvent } from '@raphaabreu/nestjs-zod-cqrs/events';

export class OrderPlacedEvent extends defineZodEvent(
  z.object({
    orderId: z.string(),
    productId: z.string(),
    quantity: z.number(),
    amount: z.number(),
  }),
) {}
// get-order.query.ts
import { z } from 'zod';
import { defineZodQuery } from '@raphaabreu/nestjs-zod-cqrs/queries';

export class GetOrderQuery extends defineZodQuery({
  input: z.object({
    orderId: z.string(),
  }),
  output: z.object({
    orderId: z.string(),
    productId: z.string(),
    quantity: z.number(),
    status: z.enum(['pending', 'shipped', 'delivered']),
  }),
}) {}

Controller

// orders.controller.ts
@Controller('orders')
export class OrdersController {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly queryBus: QueryBus,
  ) {}

  @Post()
  async placeOrder(@Body() body: PlaceOrderInput) {
    // Type-safe at assembly and validated once by the command constructor.
    const command = new PlaceOrderCommand(body);
    return this.commandBus.execute(command);
  }

  @Get(':id')
  async getOrder(@Param('id') id: string) {
    const query = new GetOrderQuery({ orderId: id });
    return this.queryBus.execute(query);
  }
}

Command handler

// place-order.handler.ts
@CommandHandler(PlaceOrderCommand)
export class PlaceOrderHandler implements ICommandHandler<PlaceOrderCommand> {
  constructor(
    private readonly orderRepo: OrderRepository,
    private readonly eventBus: EventBus,
  ) {}

  async execute(command: PlaceOrderCommand) {
    // command.productId and command.quantity are already validated
    const order = await this.orderRepo.create({
      productId: command.productId,
      quantity: command.quantity,
    });

    // Publish a validated event
    this.eventBus.publish(
      new OrderPlacedEvent({
        orderId: order.id,
        productId: order.productId,
        quantity: order.quantity,
        amount: order.amount,
      }),
    );

    // order has many internal fields (updatedAt, version, internalNotes, etc.)
    // parseOutput() strips everything not in the output schema
    return PlaceOrderCommand.parseOutput(order);
  }
}

Query handler

// get-order.handler.ts
@QueryHandler(GetOrderQuery)
export class GetOrderHandler implements IQueryHandler<GetOrderQuery> {
  constructor(private readonly orderRepo: OrderRepository) {}

  async execute(query: GetOrderQuery) {
    // The repo returns a fat internal model with audit fields, soft-delete flags, etc.
    const order = await this.orderRepo.findById(query.orderId);

    // parseOutput() validates and strips it down to just { orderId, productId, quantity, status }
    return GetOrderQuery.parseOutput(order);
  }
}

API

defineZodEvent(schema)

Returns a base class with:

  • new(input) — parse input and return a class instance (throws on failure)
  • InputSchema — the Zod schema
  • safeParseInput(raw) — safely parse input and return an event instance

defineZodCloudEvent(options)

Returns a CloudEvents 1.0 event class with:

  • new({ subject, data, id?, time? }) — validate data and create the complete envelope
  • InputSchema — the producer-input schema
  • DataSchema — the business-payload schema
  • EnvelopeSchema — the complete consumer-envelope schema
  • safeParseInput(raw) — safely parse producer input and return an outgoing event
  • parseEnvelope(raw) / safeParseEnvelope(raw) — validate an incoming envelope and return an event-class instance
  • type, source, dataschema, and subjectStartsWith — definition metadata

Ordinary z.object() payload schemas recursively strip undeclared properties from rich models. Choosing .strict() or .passthrough() retains Zod's corresponding reject-or-preserve behavior.

defineZodCommand({ input, output }) / defineZodQuery({ input, output })

Returns a base class extending Command<O> / Query<O> with:

  • new(input) — parse input and return a class instance (throws on failure)
  • InputSchema / OutputSchema — the Zod schemas
  • safeParseInput(raw) — safely parse untrusted input and return a command or query instance
  • parseOutput(output) — validate and shape a handler's return value, stripping undeclared fields (throws on failure)
  • safeParseOutput(raw) — safely validate and shape an untrusted handler result

License

MIT