KubeMQ
IntegrationsNestJSReference

API

The @kubemq/nestjs-transport API surface — KubeMQModule static methods, the five handler decorators, the request/queue contexts, codecs, and constants.

This page is the API lookup for @kubemq/nestjs-transport — the KubeMQModule static methods, the five handler decorators and their options, the per-pattern contexts, the codec exports, and the module constants and enums. For connection options and configuration interfaces see Configuration; for the error catalog see error codes. For task-oriented walkthroughs, start with Getting Started; this page is the lookup table you return to.

Module API

KubeMQModule is a dynamic module exposing seven static factory methods. forRoot / forRootAsync establish the shared connection; register / registerAsync create named client proxies for injection; forFeature / forFeatureAsync create channel-prefixed scoped clients on top of the shared connection; forTest swaps in mocks.

MethodPurpose
KubeMQModule.forRoot(options)Register the global, shared KubeMQ connection from a static KubeMQModuleOptions (global by default)
KubeMQModule.forRootAsync(options)Same, but resolve options asynchronously via useFactory / useClass / useExisting
KubeMQModule.register(options)Create a named KubeMQClientProxy for @Inject-ed message sending
KubeMQModule.registerAsync(options)Same, with async option resolution
KubeMQModule.forFeature(options)Create a ScopedKubeMQClientProxy that prepends channelPrefix to every channel, reusing the shared client
KubeMQModule.forFeatureAsync(options)Same, with async resolution of the feature options
KubeMQModule.forTest(options?)Provide a MockKubeMQClient / MockKubeMQServer for unit tests without a broker
app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { KubeMQModule } from '@kubemq/nestjs-transport';

@Module({
  imports: [
    // Shared connection (global by default)
    KubeMQModule.forRoot({
      address: 'localhost:50000',
      clientId: 'orders-app',
      isGlobal: true,
    }),

    // Async shared connection from ConfigService
    KubeMQModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (config: ConfigService) => ({
        address: config.getOrThrow('KUBEMQ_ADDRESS'),
        clientId: config.get('KUBEMQ_CLIENT_ID'),
      }),
      inject: [ConfigService],
    }),

    // Named client proxy for injection
    KubeMQModule.register({
      name: 'ORDER_SERVICE',
      address: 'localhost:50000',
      clientId: 'order-client',
    }),

    // Channel-scoped client: every channel is prefixed with "orders"
    KubeMQModule.forFeature({ name: 'ORDER_BUS', channelPrefix: 'orders' }),
  ],
})
export class AppModule {}

forRoot and forRootAsync are global by default — isGlobal defaults to true (it is treated as global unless explicitly set to false). register, registerAsync, forFeature, and forFeatureAsync are scoped to the importing module. forTest is global unless isGlobal: false is passed.

The option interfaces accepted by these methods (KubeMQModuleOptions, KubeMQClientOptions, and the async variants) are documented in Configuration.

Decorators

Five custom decorators replace the manual @MessagePattern / @EventPattern metadata you would otherwise hand-configure for each pattern. Each accepts a single channel string or an array of channels, plus an optional options object. They are exported from the package root (src/decorators/index.ts).

DecoratorPattern typeSemanticsAccepted option keys
@CommandHandler(channel, opts?)commandRequest-replybase + validate
@QueryHandler(channel, opts?)queryRequest-replybase + validate
@EventHandler(channel, opts?)eventFire-and-forgetbase + validate
@EventStoreHandler(channel, opts?)event_storeFire-and-forget, persistentbase + startFrom, startValue, validate
@QueueHandler(channel, opts?)queueAt-least-once deliverybase + manualAck, maxMessages, waitTimeoutSeconds, batch, idempotency, validate
handlers.ts
import {
  CommandHandler,
  QueryHandler,
  EventHandler,
  EventStoreHandler,
  QueueHandler,
} from '@kubemq/nestjs-transport';
import { Payload, Ctx } from '@nestjs/microservices';

@CommandHandler('orders.create', { group: 'order-writers', maxConcurrent: 5 })
handleCreate(@Payload() data: CreateOrderDto) { /* ... */ }

@QueryHandler('orders.get')
handleGet(@Payload() data: { id: string }) { /* ... */ }

// A single handler can subscribe to multiple channels
@EventHandler(['orders.updated', 'orders.created'])
onChange(@Payload() data: OrderEvent) { /* ... */ }

@EventStoreHandler('orders.history', { startFrom: 'first' })
replay(@Payload() data: unknown) { /* ... */ }

@QueueHandler('orders.process', { manualAck: true, maxMessages: 5 })
process(@Payload() data: unknown, @Ctx() ctx) { /* ... */ }

Decorator Options

All decorator option interfaces extend KubeMQHandlerBaseOptions. The base keys apply to every handler; each pattern then adds its own extras. Defaults below come from src/interfaces/decorator-options.interface.ts and src/interfaces/handler-metadata.interface.ts.

Base options (all handlers)

Prop

Type

Events Store extras (@EventStoreHandler)

Prop

Type

Queue extras (@QueueHandler)

Prop

Type

decorator-options.ts
// Replay an events-store stream from sequence 100
@EventStoreHandler('orders.history', { startFrom: 'sequence', startValue: 100 })

// Manual-ack queue with bounded concurrency and a DLQ after 3 retries
@QueueHandler('orders.process', {
  manualAck: true,
  maxMessages: 5,
  waitTimeoutSeconds: 60,
  concurrency: 4,
  deadLetterChannel: 'orders.dlq',
  maxRetries: 3,
})

// Batch processing with idempotent dedup
@QueueHandler('orders.batch', {
  batch: true,
  maxMessages: 10,
  idempotency: { ttlSeconds: 600, maxCacheSize: 50_000 },
})

Contexts

The object bound by @Ctx() is a typed context that extends BaseRpcContext. KubeMQContext is the base; per-pattern contexts add fields. Pick the context type that matches the handler decorator.

ContextAddsNotable members
KubeMQContextbasechannel, id, timestamp, tags, metadata, patternType, getCorrelationId(), getCausationId()
KubeMQCommandContextcommandfromClientId, replyChannel (re-exported from the merged request context)
KubeMQQueryContextqueryfromClientId, replyChannel (re-exported from the merged request context)
KubeMQRequestContextunionShared request context backing both command and query
KubeMQEventStoreContextevents storesequence
KubeMQQueueContextqueuesequence, receiveCount, isReRouted, reRouteFromQueue, ack(), nack(), reQueue(channel)
KubeMQQueueBatchContextbatch queuesize, getContexts(), getContext(index), ackAll(), nackAll()
contexts.ts
import {
  EventStoreHandler,
  QueueHandler,
  KubeMQEventStoreContext,
  KubeMQQueueContext,
} from '@kubemq/nestjs-transport';
import { Payload, Ctx } from '@nestjs/microservices';

@EventStoreHandler('orders.history', { startFrom: 'first' })
onHistory(@Payload() data: unknown, @Ctx() ctx: KubeMQEventStoreContext) {
  console.log(`Event #${ctx.sequence} on ${ctx.channel}`);
}

@QueueHandler('orders.process', { manualAck: true })
async onProcess(@Payload() data: unknown, @Ctx() ctx: KubeMQQueueContext) {
  console.log(`Delivery #${ctx.receiveCount}, re-routed: ${ctx.isReRouted}`);
  try {
    await handle(data);
    ctx.ack();
  } catch {
    ctx.reQueue('orders.dlq'); // or ctx.nack()
  }
}

ack(), nack(), and reQueue() (and the batch ackAll() / nackAll()) are only available when the handler is declared with { manualAck: true }. Calling them in auto-ack mode throws an Error.

Codecs

The default codec is JSON. Swap in MessagePack or Protobuf by passing a serializer/deserializer pair to the server, client, or CQRS options. Custom codecs implement the KubeMQSerializer / KubeMQDeserializer interfaces.

ExportDescription
KubeMQSerializerInterface: serialize(value): Uint8Array
KubeMQDeserializerInterface: deserialize(data, tags?): any
JsonSerializer / JsonDeserializerDefault JSON codec pair
MessagePackSerializer / MessagePackDeserializerMessagePack codec (requires @msgpack/msgpack)
ProtobufSerializer / ProtobufDeserializerProtobuf codec (requires protobufjs)
codecs.ts
import { KubeMQServer, MessagePackSerializer, MessagePackDeserializer } from '@kubemq/nestjs-transport';

new KubeMQServer({
  address: 'localhost:50000',
  serializer: new MessagePackSerializer(),
  deserializer: new MessagePackDeserializer(),
});

The sender and receiver must use the same codec. If a MessagePackSerializer produces bytes that a JsonDeserializer tries to parse, a SerializationError is thrown on the receiving side.

Constants & Enums

Exported tokens, metadata keys, message tags, and enums. The injection token and metadata-key constants come from src/constants.ts; KubeMQStatus is from src/events/kubemq.events.ts; EventStoreStartFrom is the start-position type.

ExportTypeValue / shape
KUBEMQ_TRANSPORTstring'kubemq' — transport identifier
KUBEMQ_MODULE_OPTIONSstring'KUBEMQ_MODULE_OPTIONS' — injection token for module options
KUBEMQ_HANDLER_METADATAstring'kubemq:handler' — metadata key for decorator options
TAG_PATTERNstring'nestjs:pattern'
TAG_IDstring'nestjs:id'
TAG_TYPEstring'nestjs:type'
TAG_CONTENT_TYPEstring'nestjs:content-type'
TAG_CORRELATION_IDstring'x-correlation-id'
TAG_CAUSATION_IDstring'x-causation-id'
TAG_IDEMPOTENCY_KEYstring'x-idempotency-key'
TAG_TRACEPARENTstring'traceparent'
TAG_TRACESTATEstring'tracestate'
KubeMQPatternTypetype'command' | 'query' | 'event' | 'event_store' | 'queue'
KubeMQStatusenumDISCONNECTED 'disconnected', RECONNECTING 'reconnecting', CONNECTED 'connected', CLOSED 'closed'
EventStoreStartFromtype'new' | 'first' | 'last' | 'sequence' | 'time' | 'timeDelta' | 1 | 2 | 3 | 4 | 5 | 6

There is no exported KUBEMQ_CLIENT_TOKEN constant — choose your own string or symbol token for register / forTest. When forTest is called without a name, it defaults the injection token to the string 'KUBEMQ_SERVICE'.

See Also

Was this page helpful?

On this page