Skip to content

@amqp-contract/contract


@amqp-contract/contract

Type Aliases

AnySchema

ts
type AnySchema = StandardSchemaV1;

Defined in: types.ts:12

Any schema that conforms to Standard Schema v1.

This library supports any validation library that implements the Standard Schema v1 specification, including Zod, Valibot, and ArkType. This allows you to use your preferred validation library while maintaining type safety.

See

https://github.com/standard-schema/standard-schema


BaseExchangeDefinition

ts
type BaseExchangeDefinition = object;

Defined in: types.ts:50

Base definition of an AMQP exchange.

An exchange receives messages from publishers and routes them to queues based on the exchange type and routing rules. This type contains properties common to all exchange types.

Properties

PropertyTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for advanced configuration. Common arguments include alternate-exchange for handling unroutable messages.types.ts:79
autoDelete?booleanIf true, the exchange is deleted when all queues have finished using it. Default falsetypes.ts:66
durable?booleanIf true, the exchange survives broker restarts. Durable exchanges are persisted to disk. Default falsetypes.ts:60
internal?booleanIf true, the exchange cannot be directly published to by clients. It can only receive messages from other exchanges via exchange-to-exchange bindings. Default falsetypes.ts:73
namestringThe name of the exchange. Must be unique within the RabbitMQ virtual host.types.ts:54

BindingDefinition

ts
type BindingDefinition = 
  | QueueBindingDefinition
  | ExchangeBindingDefinition;

Defined in: types.ts:370

Union type of all binding definitions.

A binding can be either:

  • Queue-to-exchange binding: Routes messages from an exchange to a queue
  • Exchange-to-exchange binding: Forwards messages from one exchange to another

BindingPattern

ts
type BindingPattern<S> = S extends "" ? never : S;

Defined in: builder.ts:844

Type-safe binding pattern that validates basic format and wildcards.

Validates that a binding pattern follows basic AMQP binding pattern rules:

  • Can contain wildcards (* for one word, # for zero or more words)
  • Must not be empty
  • Should contain alphanumeric characters, dots, hyphens, underscores, and wildcards

Note: Full character-by-character validation is not performed to avoid TypeScript recursion depth limits. Runtime validation is still recommended.

Type Parameters

Type ParameterDescription
S extends stringThe binding pattern string to validate

Example

typescript
type ValidPattern = BindingPattern<"order.*">; // "order.*"
type ValidHash = BindingPattern<"order.#">; // "order.#"
type ValidConcrete = BindingPattern<"order.created">; // "order.created"
type Invalid = BindingPattern<"">; // never (empty string)

CompressionAlgorithm

ts
type CompressionAlgorithm = "gzip" | "deflate";

Defined in: types.ts:42

Supported compression algorithms for message payloads.

  • gzip: GZIP compression (standard, widely supported, good compression ratio)
  • deflate: DEFLATE compression (faster than gzip, slightly less compression)

Compression is configured at runtime via PublishOptions when calling AmqpClient.publish, not at publisher definition time.

When compression is enabled, the message payload is compressed before publishing and automatically decompressed when consuming. The content-encoding AMQP message property is set to indicate the compression algorithm used.

To disable compression, simply omit the compression option (it's optional).

Example

typescript
// Define a publisher without compression configuration
const orderCreatedPublisher = definePublisher(exchange, message, {
  routingKey: "order.created",
});

// Later, choose whether to compress at publish time
await client.publish("orderCreated", payload, {
  compression: "gzip",
});

ConsumerDefinition

ts
type ConsumerDefinition<TMessage> = object;

Defined in: types.ts:431

Definition of a message consumer.

A consumer receives and processes messages from a queue with automatic schema validation. The message payload is validated against the schema before being passed to your handler. If the message is compressed (indicated by the content-encoding header), it will be automatically decompressed before validation.

Example

typescript
const consumer: ConsumerDefinition = {
  queue: orderProcessingQueue,
  message: orderMessage
};

Type Parameters

Type ParameterDefault typeDescription
TMessage extends MessageDefinitionMessageDefinitionThe message definition with payload schema

Properties

PropertyTypeDescriptionDefined in
messageTMessageThe message definition including the payload schematypes.ts:436
queueQueueDefinitionThe queue to consume messages fromtypes.ts:433

ConsumerFirstResult

ts
type ConsumerFirstResult<TMessage, TConsumer, TBinding> = object;

Defined in: builder.ts:1221

Consumer-first builder result for fanout and direct exchanges.

This type represents a consumer with its binding and provides a method to create a publisher that uses the same message schema and routing key.

Type Parameters

Type ParameterDescription
TMessage extends MessageDefinitionThe message definition
TConsumer extends ConsumerDefinition<TMessage>The consumer definition
TBinding extends QueueBindingDefinitionThe queue binding definition

Properties

PropertyTypeDescriptionDefined in
bindingTBindingThe binding definition connecting the exchange to the queuebuilder.ts:1229
consumerTConsumerThe consumer definitionbuilder.ts:1227
createPublisher() => TBinding["exchange"] extends FanoutExchangeDefinition ? Extract<PublisherDefinition<TMessage>, { exchange: FanoutExchangeDefinition; }> : Extract<PublisherDefinition<TMessage>, { exchange: | DirectExchangeDefinition | TopicExchangeDefinition; }>Create a publisher that sends messages to this consumer. The publisher will automatically use the same message schema and routing key.builder.ts:1236

ConsumerFirstResultWithRoutingKey

ts
type ConsumerFirstResultWithRoutingKey<TMessage, TConsumer, TBinding> = object;

Defined in: builder.ts:1254

Consumer-first builder result for topic exchanges.

This type represents a consumer with its binding (which may use a pattern) and provides a method to create a publisher with a concrete routing key that matches the pattern.

Type Parameters

Type ParameterDescription
TMessage extends MessageDefinitionThe message definition
TConsumer extends ConsumerDefinition<TMessage>The consumer definition
TBinding extends QueueBindingDefinitionThe queue binding definition

Properties

PropertyTypeDescriptionDefined in
bindingTBindingThe binding definition connecting the exchange to the queuebuilder.ts:1262
consumerTConsumerThe consumer definitionbuilder.ts:1260
createPublisher<TPublisherRoutingKey>(routingKey) => Extract<PublisherDefinition<TMessage>, { exchange: | DirectExchangeDefinition | TopicExchangeDefinition; }>Create a publisher that sends messages to this consumer. For topic exchanges, the routing key can be specified to match the binding pattern.builder.ts:1270

ContractDefinition

ts
type ContractDefinition = object;

Defined in: types.ts:472

Complete AMQP contract definition.

A contract brings together all AMQP resources into a single, type-safe definition. It defines the complete messaging topology including exchanges, queues, bindings, publishers, and consumers.

The contract is used by:

  • Clients (TypedAmqpClient) for type-safe message publishing
  • Workers (TypedAmqpWorker) for type-safe message consumption
  • AsyncAPI generator for documentation

Example

typescript
const contract: ContractDefinition = {
  exchanges: {
    orders: ordersExchange,
  },
  queues: {
    orderProcessing: orderProcessingQueue,
  },
  bindings: {
    orderBinding: orderQueueBinding,
  },
  publishers: {
    orderCreated: orderCreatedPublisher,
  },
  consumers: {
    processOrder: processOrderConsumer,
  },
};

Properties

PropertyTypeDescriptionDefined in
bindings?Record<string, BindingDefinition>Named binding definitions. Bindings can be queue-to-exchange or exchange-to-exchange.types.ts:489
consumers?Record<string, ConsumerDefinition>Named consumer definitions. Each key requires a corresponding handler in the TypedAmqpWorker. The handler will be fully typed based on the message schema.types.ts:503
exchanges?Record<string, ExchangeDefinition>Named exchange definitions. Each key becomes available as a named resource in the contract.types.ts:477
publishers?Record<string, PublisherDefinition>Named publisher definitions. Each key becomes a method on the TypedAmqpClient for publishing messages. The method will be fully typed based on the message schema.types.ts:496
queues?Record<string, QueueDefinition>Named queue definitions. Each key becomes available as a named resource in the contract.types.ts:483

DeadLetterConfig

ts
type DeadLetterConfig = object;

Defined in: types.ts:154

Configuration for dead letter exchange (DLX) on a queue.

When a message in a queue is rejected, expires, or exceeds the queue length limit, it can be automatically forwarded to a dead letter exchange for further processing or storage.

Properties

PropertyTypeDescriptionDefined in
exchangeExchangeDefinitionThe exchange to send dead-lettered messages to. This exchange must be declared in the contract.types.ts:159
routingKey?stringOptional routing key to use when forwarding messages to the dead letter exchange. If not specified, the original message routing key is used.types.ts:165

DirectExchangeDefinition

ts
type DirectExchangeDefinition = BaseExchangeDefinition & object;

Defined in: types.ts:112

A direct exchange definition.

Direct exchanges route messages to queues based on exact routing key matches. This is ideal for point-to-point messaging where each message should go to specific queues.

Type Declaration

NameTypeDefined in
type"direct"types.ts:113

Example

typescript
const tasksExchange: DirectExchangeDefinition = defineExchange('tasks', 'direct', {
  durable: true
});

ExchangeBindingDefinition

ts
type ExchangeBindingDefinition = object & 
  | {
  routingKey: string;
  source:   | DirectExchangeDefinition
     | TopicExchangeDefinition;
}
  | {
  routingKey?: never;
  source: FanoutExchangeDefinition;
};

Defined in: types.ts:334

Binding between two exchanges (exchange-to-exchange routing).

Defines how messages should be forwarded from a source exchange to a destination exchange. This allows for more complex routing topologies.

Type Declaration

NameTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for the binding.types.ts:344
destinationExchangeDefinitionThe destination exchange that will receive forwarded messagestypes.ts:339
type"exchange"Discriminator indicating this is an exchange-to-exchange bindingtypes.ts:336

Example

typescript
// Forward high-priority orders to a special processing exchange
const binding: ExchangeBindingDefinition = {
  type: 'exchange',
  source: ordersExchange,
  destination: highPriorityExchange,
  routingKey: 'order.high-priority.*'
};

ExchangeDefinition

ts
type ExchangeDefinition = 
  | FanoutExchangeDefinition
  | DirectExchangeDefinition
  | TopicExchangeDefinition;

Defined in: types.ts:142

Union type of all exchange definitions.

Represents any type of AMQP exchange: fanout, direct, or topic.


FanoutExchangeDefinition

ts
type FanoutExchangeDefinition = BaseExchangeDefinition & object;

Defined in: types.ts:95

A fanout exchange definition.

Fanout exchanges broadcast all messages to all bound queues, ignoring routing keys. This is the simplest exchange type for pub/sub messaging patterns.

Type Declaration

NameTypeDefined in
type"fanout"types.ts:96

Example

typescript
const logsExchange: FanoutExchangeDefinition = defineExchange('logs', 'fanout', {
  durable: true
});

InferConsumerNames

ts
type InferConsumerNames<TContract> = TContract["consumers"] extends Record<string, unknown> ? keyof TContract["consumers"] : never;

Defined in: types.ts:539

Extract consumer names from a contract.

This utility type extracts the keys of all consumers defined in a contract. It's used internally for type inference in the TypedAmqpWorker.

Type Parameters

Type ParameterDescription
TContract extends ContractDefinitionThe contract definition

Returns

Union of consumer names, or never if no consumers defined

Example

typescript
type ConsumerNames = InferConsumerNames<typeof myContract>;
// Result: 'processOrder' | 'sendNotification' | 'updateInventory'

InferPublisherNames

ts
type InferPublisherNames<TContract> = TContract["publishers"] extends Record<string, unknown> ? keyof TContract["publishers"] : never;

Defined in: types.ts:521

Extract publisher names from a contract.

This utility type extracts the keys of all publishers defined in a contract. It's used internally for type inference in the TypedAmqpClient.

Type Parameters

Type ParameterDescription
TContract extends ContractDefinitionThe contract definition

Returns

Union of publisher names, or never if no publishers defined

Example

typescript
type PublisherNames = InferPublisherNames<typeof myContract>;
// Result: 'orderCreated' | 'orderUpdated' | 'orderCancelled'

MatchingRoutingKey

ts
type MatchingRoutingKey<Pattern, Key> = RoutingKey<Key> extends never ? never : BindingPattern<Pattern> extends never ? never : MatchesPattern<Key, Pattern> extends true ? Key : never;

Defined in: builder.ts:906

Validate that a routing key matches a binding pattern.

This is a utility type provided for users who want compile-time validation that a routing key matches a specific pattern. It's not enforced internally in the API to avoid TypeScript recursion depth issues with complex routing keys.

Returns the routing key if it's valid and matches the pattern, never otherwise.

Type Parameters

Type ParameterDescription
Pattern extends stringThe binding pattern (can contain * and # wildcards)
Key extends stringThe routing key to validate

Example

typescript
type ValidKey = MatchingRoutingKey<"order.*", "order.created">; // "order.created"
type InvalidKey = MatchingRoutingKey<"order.*", "user.created">; // never

MessageDefinition

ts
type MessageDefinition<TPayload, THeaders> = object;

Defined in: types.ts:250

Definition of a message with typed payload and optional headers.

Type Parameters

Type ParameterDefault typeDescription
TPayload extends AnySchemaAnySchemaThe Standard Schema v1 compatible schema for the message payload
THeaders extends StandardSchemaV1<Record<string, unknown>> | undefinedundefinedThe Standard Schema v1 compatible schema for the message headers (optional)

Properties

PropertyTypeDescriptionDefined in
description?stringDetailed description of the message for documentation purposes. Used in AsyncAPI specification generation.types.ts:276
headers?THeadersOptional headers schema for validating message metadata. Must be a Standard Schema v1 compatible schema.types.ts:264
payloadTPayloadThe payload schema for validating message content. Must be a Standard Schema v1 compatible schema (Zod, Valibot, ArkType, etc.).types.ts:258
summary?stringBrief description of the message for documentation purposes. Used in AsyncAPI specification generation.types.ts:270

PublisherDefinition

ts
type PublisherDefinition<TMessage> = object & 
  | {
  exchange:   | DirectExchangeDefinition
     | TopicExchangeDefinition;
  routingKey: string;
}
  | {
  exchange: FanoutExchangeDefinition;
  routingKey?: never;
};

Defined in: types.ts:392

Definition of a message publisher.

A publisher sends messages to an exchange with automatic schema validation. The message payload is validated against the schema before being sent to RabbitMQ.

Compression can be optionally applied at publish time by specifying a compression algorithm when calling the publish method.

Type Declaration

NameTypeDescriptionDefined in
messageTMessageThe message definition including the payload schematypes.ts:394

Type Parameters

Type ParameterDefault typeDescription
TMessage extends MessageDefinitionMessageDefinitionThe message definition with payload schema

Example

typescript
const publisher: PublisherDefinition = {
  exchange: ordersExchange,
  message: orderMessage,
  routingKey: 'order.created'
};

PublisherFirstResult

ts
type PublisherFirstResult<TMessage, TPublisher> = object;

Defined in: builder.ts:773

Publisher-first builder result for fanout and direct exchanges.

This type represents a publisher and provides a method to create a consumer that uses the same message schema with a binding to the exchange.

This pattern is suitable for event-oriented messaging where publishers emit events without knowing which queues will consume them.

Type Parameters

Type ParameterDescription
TMessage extends MessageDefinitionThe message definition
TPublisher extends PublisherDefinition<TMessage>The publisher definition

Properties

PropertyTypeDescriptionDefined in
createConsumer(queue) => objectCreate a consumer that receives messages from this publisher. The consumer will automatically use the same message schema and a binding will be created with the same routing key.builder.ts:787
publisherTPublisherThe publisher definitionbuilder.ts:778

PublisherFirstResultWithRoutingKey

ts
type PublisherFirstResultWithRoutingKey<TMessage, TPublisher, TRoutingKey> = object;

Defined in: builder.ts:925

Publisher-first builder result for topic exchanges.

This type represents a publisher with a concrete routing key and provides a method to create consumers that can use routing key patterns matching the publisher's key.

Type Parameters

Type ParameterDescription
TMessage extends MessageDefinitionThe message definition
TPublisher extends PublisherDefinition<TMessage>The publisher definition
TRoutingKey extends stringThe literal routing key type from the publisher (for documentation purposes)

Properties

PropertyTypeDescriptionDefined in
createConsumer<TConsumerRoutingKey>(queue, routingKey?) => objectCreate a consumer that receives messages from this publisher. For topic exchanges, the routing key pattern can be specified for the binding.builder.ts:940
publisherTPublisherThe publisher definitionbuilder.ts:931

QueueBindingDefinition

ts
type QueueBindingDefinition = object & 
  | {
  exchange:   | DirectExchangeDefinition
     | TopicExchangeDefinition;
  routingKey: string;
}
  | {
  exchange: FanoutExchangeDefinition;
  routingKey?: never;
};

Defined in: types.ts:286

Binding between a queue and an exchange.

Defines how messages from an exchange should be routed to a queue. For direct and topic exchanges, a routing key is required. For fanout exchanges, no routing key is needed as all messages are broadcast.

Type Declaration

NameTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for the binding. Can be used for advanced routing scenarios with the headers exchange type.types.ts:297
queueQueueDefinitionThe queue that will receive messagestypes.ts:291
type"queue"Discriminator indicating this is a queue-to-exchange bindingtypes.ts:288

QueueDefinition

ts
type QueueDefinition = object;

Defined in: types.ts:174

Definition of an AMQP queue.

A queue stores messages until they are consumed by workers. Queues are bound to exchanges to receive messages based on routing rules.

Properties

PropertyTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for advanced configuration. Common arguments include: - x-message-ttl: Message time-to-live in milliseconds - x-expires: Queue expiration time in milliseconds - x-max-length: Maximum number of messages in the queue - x-max-length-bytes: Maximum size of the queue in bytes - x-max-priority: Maximum priority level for priority queues Note: When using the deadLetter property, the x-dead-letter-exchange and x-dead-letter-routing-key arguments are automatically set and should not be specified in this arguments object. Example { 'x-message-ttl': 86400000, // 24 hours 'x-max-priority': 10 }types.ts:241
autoDelete?booleanIf true, the queue is deleted when the last consumer unsubscribes. Default falsetypes.ts:197
deadLetter?DeadLetterConfigDead letter configuration for handling failed or rejected messages. When configured, messages that are rejected, expire, or exceed queue limits will be automatically forwarded to the specified dead letter exchange. Example const dlx = defineExchange('orders-dlx', 'topic', { durable: true }); const queue = defineQueue('order-processing', { durable: true, deadLetter: { exchange: dlx, routingKey: 'order.failed' } });types.ts:217
durable?booleanIf true, the queue survives broker restarts. Durable queues are persisted to disk. Default falsetypes.ts:184
exclusive?booleanIf true, the queue can only be used by the declaring connection and is deleted when that connection closes. Exclusive queues are private to the connection. Default falsetypes.ts:191
namestringThe name of the queue. Must be unique within the RabbitMQ virtual host.types.ts:178

RoutingKey

ts
type RoutingKey<S> = S extends "" ? never : S extends `${string}*${string}` | `${string}#${string}` ? never : S;

Defined in: builder.ts:817

Type-safe routing key that validates basic format.

Validates that a routing key follows basic AMQP routing key rules:

  • Must not contain wildcards (* or #)
  • Must not be empty
  • Should contain alphanumeric characters, dots, hyphens, and underscores

Note: Full character-by-character validation is not performed to avoid TypeScript recursion depth limits. Runtime validation is still recommended.

Type Parameters

Type ParameterDescription
S extends stringThe routing key string to validate

Example

typescript
type Valid = RoutingKey<"order.created">; // "order.created"
type Invalid = RoutingKey<"order.*">; // never (contains wildcard)
type Invalid2 = RoutingKey<"">; // never (empty string)

TopicExchangeDefinition

ts
type TopicExchangeDefinition = BaseExchangeDefinition & object;

Defined in: types.ts:133

A topic exchange definition.

Topic exchanges route messages to queues based on routing key patterns with wildcards:

  • * (star) matches exactly one word
  • # (hash) matches zero or more words

Words are separated by dots (e.g., order.created.high-value).

Type Declaration

NameTypeDefined in
type"topic"types.ts:134

Example

typescript
const ordersExchange: TopicExchangeDefinition = defineExchange('orders', 'topic', {
  durable: true
});
// Can be bound with patterns like 'order.*' or 'order.#'

Functions

defineConsumer()

ts
function defineConsumer<TMessage>(
   queue, 
   message, 
options?): ConsumerDefinition<TMessage>;

Defined in: builder.ts:634

Define a message consumer.

A consumer receives and processes messages from a queue. The message schema is validated automatically when messages are consumed, ensuring type safety for your handlers.

Consumers are associated with a specific queue and message type. When you create a worker with this consumer, it will process messages from the queue according to the schema.

Type Parameters

Type Parameter
TMessage extends MessageDefinition

Parameters

ParameterTypeDescription
queueQueueDefinitionThe queue definition to consume from
messageTMessageThe message definition with payload schema
options?Omit<ConsumerDefinition<TMessage>, "queue" | "message">Optional consumer configuration

Returns

ConsumerDefinition<TMessage>

A consumer definition with inferred message types

Example

typescript
import { z } from 'zod';

const orderQueue = defineQueue('order-processing', { durable: true });
const orderMessage = defineMessage(
  z.object({
    orderId: z.string().uuid(),
    customerId: z.string().uuid(),
    amount: z.number().positive(),
  })
);

const processOrderConsumer = defineConsumer(orderQueue, orderMessage);

// Later, when creating a worker, you'll provide a handler for this consumer:
// const worker = await TypedAmqpWorker.create({
//   contract,
//   handlers: {
//     processOrder: async (message) => {
//       // message is automatically typed based on the schema
//       console.log(message.orderId); // string
//     }
//   },
//   connection
// });

defineContract()

ts
function defineContract<TContract>(definition): TContract;

Defined in: builder.ts:715

Define an AMQP contract.

A contract is the central definition of your AMQP messaging topology. It brings together all exchanges, queues, bindings, publishers, and consumers in a single, type-safe definition.

The contract is used by both clients (for publishing) and workers (for consuming) to ensure type safety throughout your messaging infrastructure. TypeScript will infer all message types and publisher/consumer names from the contract.

Type Parameters

Type Parameter
TContract extends ContractDefinition

Parameters

ParameterTypeDescription
definitionTContractThe contract definition containing all AMQP resources

Returns

TContract

The same contract definition with full type inference

Example

typescript
import {
  defineContract,
  defineExchange,
  defineQueue,
  defineQueueBinding,
  definePublisher,
  defineConsumer,
  defineMessage,
} from '@amqp-contract/contract';
import { z } from 'zod';

// Define resources
const ordersExchange = defineExchange('orders', 'topic', { durable: true });
const orderQueue = defineQueue('order-processing', { durable: true });
const orderMessage = defineMessage(
  z.object({
    orderId: z.string(),
    amount: z.number(),
  })
);

// Compose contract
export const contract = defineContract({
  exchanges: {
    orders: ordersExchange,
  },
  queues: {
    orderProcessing: orderQueue,
  },
  bindings: {
    orderBinding: defineQueueBinding(orderQueue, ordersExchange, {
      routingKey: 'order.created',
    }),
  },
  publishers: {
    orderCreated: definePublisher(ordersExchange, orderMessage, {
      routingKey: 'order.created',
    }),
  },
  consumers: {
    processOrder: defineConsumer(orderQueue, orderMessage),
  },
});

// TypeScript now knows:
// - client.publish('orderCreated', { orderId: string, amount: number })
// - handler: async (message: { orderId: string, amount: number }) => void

defineMessage()

ts
function defineMessage<TPayload, THeaders>(payload, options?): MessageDefinition<TPayload, THeaders>;

Defined in: builder.ts:236

Define a message definition with payload and optional headers/metadata.

A message definition specifies the schema for message payloads and headers using Standard Schema v1 compatible libraries (Zod, Valibot, ArkType, etc.). The schemas are used for automatic validation when publishing or consuming messages.

Type Parameters

Type ParameterDefault type
TPayload extends AnySchema-
THeaders extends | StandardSchemaV1<Record<string, unknown>, Record<string, unknown>> | undefinedundefined

Parameters

ParameterTypeDescription
payloadTPayloadThe payload schema (must be Standard Schema v1 compatible)
options?{ description?: string; headers?: THeaders; summary?: string; }Optional message metadata
options.description?stringDetailed description for documentation (used in AsyncAPI generation)
options.headers?THeadersOptional header schema for message headers
options.summary?stringBrief description for documentation (used in AsyncAPI generation)

Returns

MessageDefinition<TPayload, THeaders>

A message definition with inferred types

Example

typescript
import { z } from 'zod';

const orderMessage = defineMessage(
  z.object({
    orderId: z.string().uuid(),
    customerId: z.string().uuid(),
    amount: z.number().positive(),
    items: z.array(z.object({
      productId: z.string(),
      quantity: z.number().int().positive(),
    })),
  }),
  {
    summary: 'Order created event',
    description: 'Emitted when a new order is created in the system'
  }
);

defineQueue()

ts
function defineQueue(name, options?): QueueDefinition;

Defined in: builder.ts:170

Define an AMQP queue.

A queue stores messages until they are consumed by workers. Queues can be bound to exchanges to receive messages based on routing rules.

Parameters

ParameterTypeDescription
namestringThe name of the queue
options?Omit<QueueDefinition, "name"> & objectOptional queue configuration

Returns

QueueDefinition

A queue definition

Example

typescript
// Basic queue
const orderQueue = defineQueue('order-processing', {
  durable: true,
});

// Priority queue with max priority of 10
const taskQueue = defineQueue('urgent-tasks', {
  durable: true,
  maxPriority: 10,
});

// Queue with dead letter exchange
const dlx = defineExchange('orders-dlx', 'topic', { durable: true });
const orderQueueWithDLX = defineQueue('order-processing', {
  durable: true,
  deadLetter: {
    exchange: dlx,
    routingKey: 'order.failed'
  },
  arguments: {
    'x-message-ttl': 86400000, // 24 hours
  }
});

Released under the MIT License.