@Subscribe Decorator
@Subscribe marks a provider method as a message handler. Handlers are discovered and subscribed automatically on application startup (via DiscoveryModule, imported by the plugin).
Usage
typescript
import { Injectable } from '@nestjs/common';
import { Subscribe, IPubSubMessage } from '@nestjs-redisx/pubsub';
import { UserCreatedEvent, NotificationGateway } from './types';
@Injectable()
export class UserEventsHandler {
constructor(private readonly gateway: NotificationGateway) {}
// Auto-subscribed on startup via discovery.
@Subscribe('user.created')
onUserCreated(message: IPubSubMessage<UserCreatedEvent>): void {
this.gateway.broadcast('user:new', message.data);
}
// Redis glob patterns: *, ?, [..]
@Subscribe({ pattern: 'order.*' })
onAnyOrderEvent(message: IPubSubMessage): void {
// message.pattern === 'order.*', message.channel === concrete channel
this.gateway.broadcast(message.channel, message.data);
}
}Forms
| Form | Meaning |
|---|---|
@Subscribe('user.created') | Exact channel subscription |
@Subscribe({ channel: 'user.created' }) | Same, options form |
@Subscribe({ pattern: 'user.*' }) | PSUBSCRIBE with a Redis glob (*, ?, [..]) |
Passing both channel and pattern (or neither) throws at decoration time.
The message argument
Handlers receive an IPubSubMessage<T>:
typescript
interface IPubSubMessage<T = unknown> {
channel: string; // logical channel (channelPrefix stripped)
pattern?: string; // matching pattern (pattern subscriptions only)
data: T; // JSON-parsed payload (raw string if not JSON)
raw: string; // payload exactly as received
}Behaviour
- Handler errors (sync throws and async rejections) are caught and logged — one failing handler never breaks the others or the subscriber connection.
- Multiple decorated methods on any providers may target the same channel; they share one underlying Redis subscription.
- Handlers are bound to their provider instance (
thisworks).