Skip to content

Latest commit

 

History

History
153 lines (118 loc) · 5.61 KB

File metadata and controls

153 lines (118 loc) · 5.61 KB
amqp-contract

amqp-contract

Type-safe contracts for AMQP/RabbitMQ messaging with TypeScript

CI npm version npm downloads TypeScript License: MIT

Documentation · Get Started · Examples

Why amqp-contract?

Define your AMQP contracts once — get type safety, autocompletion, and runtime validation everywhere.

  • 🔒 End-to-end type safety — TypeScript knows your message shapes
  • 🔄 Reliable retry — Built-in exponential backoff with Dead Letter Queue support
  • 📄 AsyncAPI compatible — Generate documentation from your contracts

Quick Example

import {
  defineContract,
  defineEventConsumer,
  defineEventPublisher,
  defineExchange,
  defineMessage,
  defineQueue,
} from "@amqp-contract/contract";
import { TypedAmqpClient } from "@amqp-contract/client";
import { TypedAmqpWorker } from "@amqp-contract/worker";
import { Ok } from "unthrown";
import { z } from "zod";

// 1. Define resources with Dead Letter Exchange and retry configuration
const ordersExchange = defineExchange("orders");
const ordersDlx = defineExchange("orders-dlx");
const orderProcessingQueue = defineQueue("order-processing", {
  deadLetter: { exchange: ordersDlx, routingKey: "order.failed" },
  retry: { mode: "ttl-backoff", maxRetries: 3, initialDelayMs: 1000 }, // Retry configured at queue level
});

// 2. Define message with schema validation
const orderMessage = defineMessage(
  z.object({
    orderId: z.string(),
    amount: z.number(),
  }),
);

// 3. Event pattern: publisher broadcasts, consumers subscribe
const orderCreatedEvent = defineEventPublisher(ordersExchange, orderMessage, {
  routingKey: "order.created",
});

// 4. Define contract - only publishers and consumers needed
//    Exchanges, queues, and bindings are automatically extracted
const contract = defineContract({
  publishers: {
    orderCreated: orderCreatedEvent,
  },
  consumers: {
    processOrder: defineEventConsumer(orderCreatedEvent, orderProcessingQueue),
  },
});

// 5. Type-safe consuming with automatic retry (configured at queue level)
const worker = (
  await TypedAmqpWorker.create({
    contract,
    handlers: {
      processOrder: ({ payload }) => {
        console.log(payload.orderId); // ✅ TypeScript knows!
        return Ok(undefined).toAsync();
      },
    },
    urls: ["amqp://localhost"],
  })
).unwrap();

// 6. Type-safe publishing with validation
const client = (
  await TypedAmqpClient.create({
    contract,
    urls: ["amqp://localhost"],
  })
).unwrap();

// publish() returns an AsyncResult instead of throwing — awaiting it yields
// a Result to unwrap() (or .match()) so failures surface. See the error
// model guide for details.
(
  await client.publish("orderCreated", {
    orderId: "ORD-123", // ✅ TypeScript knows!
    amount: 99.99,
  })
).unwrap();

// 7. Clean up
(await client.close()).unwrap();
(await worker.close()).unwrap();

▶ For the full runnable version (including the RabbitMQ Docker command), follow the 5-minute quick start.

Installation

Requires Node.js 22.19+.

pnpm add @amqp-contract/contract @amqp-contract/client @amqp-contract/worker unthrown zod

unthrown is exposed in the public types (AsyncResult<void, HandlerError>), so consumers need it directly to construct handler results. zod can be swapped for any Standard Schema library (Valibot, ArkType, …).

Need a local RabbitMQ to try it against?

docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:4-management

Documentation

📖 Full Documentation →

Packages

Package Description
@amqp-contract/contract Contract builder and type definitions
@amqp-contract/client Type-safe client for publishing
@amqp-contract/worker Type-safe worker with retry support
@amqp-contract/asyncapi AsyncAPI 3.0 generator

Contributing

See CONTRIBUTING.md.

License

MIT