This is a custom transport strategy wrapper for Google Cloud Pub/Sub within the NestJS framework. In other words, it provides a simple way to publish and subscribe to a topic.
This service is built with Node (v16.14.2
using npm@8.5.0
) and NestJS.
npm install @softrizon/pubsub
- Module configuration
import { Module } from '@nestjs/common';
import { PubSubModule } from '@softrizon/pubsub';
import { MessageService } from './message.service';
@Module({
imports: [
PubSubModule.forRoot({
defaultTopicName: 'my-topic',
defaultFormat: 'my-format',
config: { projectId: 'my-project' },
}),
],
providers: [MessageService],
})
export class AppModule {}
- Inject the service (e.g.,
MessageService
) to emit messages.
import { Injectable } from '@nestjs/common';
import { PubSubService } from '@softrizon/pubsub';
@Injectable()
export class MessageService {
constructor(private pubsub: PubSubService) {}
emit<T = any>(pattern: string, data: T): void {
const emitOptions = {
event: pattern;
data: data;
topic: 'another-topic'; // optional, default: defaultTopicName
format: 'another-format'; // optional, default: defaultFormat
}
this.pubsub.emit(emitOptions);
}
}
- Server configuration
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions } from '@nestjs/microservices';
import { PubSubServer } from '@softrizon/pubsub';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.connectMicroservice<MicroserviceOptions>({
strategy: new PubSubServer({
config: { projectId: 'my-project' },
topic: 'my-topic',
subscriptions: ['my-subscription'],
}),
});
app.startAllMicroservices();
await app.listen(3000);
}
bootstrap();
- Subscribe to message pattern
import { Controller } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
@Controller()
export class MessagesEventController {
@MessagePattern({ event: 'MY_PATTERN', format: 'JSON_API_V1' })
async doSomething(@Payload() data: any): Promise<void> {
// do something with data...
}
}
Note: Do not forget to register the controller in the corresponding module. In the example above, the message pattern is an object with the keys
event
andformat
. This is a practice useful for filtering events in the one-to-many pubsub architecture. If you don't need this kind of filtering, you may need to extendPubSubServer
and override thehandleMessage
andgetData
methods.
Visit the main page to learn more about its key features, configurations, limitations, and API.
Developed by Softrizon.
This project is MIT-licensed.