@swang-dev/nestjs-gcp-pubsub
v1.0.0
Published
NestJS library for Google Cloud Pub/Sub
Downloads
52
Readme
@swang-dev/nestjs-gcp-pubsub
Description
A simple module following NestJS recommendations for creating a microservice for GCP PubSub. This library contains a custom transporter for subscribing and a module for publishing.
Installation
npm i --save @@swang-dev/nestjs-gcp-pubsubQuick Start
Client (Publisher)
Import GcpPubSubClientModule:
// Module
import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'
import { GcpPubSubClientModule } from '@swang-dev/nestjs-gcp-pubsub'
@Module({
controllers: [],
providers: [],
imports: [
// forRoot configuration
GcpPubSubClientModule.forRoot({
prefix: 'test',
topics: [{ name: 'topic' }],
clientConfig: {
projectId: 'test-project',
credentials: {
client_email: '[email protected]',
private_key: 'fake',
},
},
}),
// forRootAsync configuration
GcpPubSubClientModule.forRootAsync({
useFactory: () => ({
prefix: 'test',
topics: [{ name: 'topic' }, { name: 'topic-2' }, { name: 'topic-3' }],
clientConfig: {
projectId: 'test-project',
apiEndpoint: 'localhost:8085',
emulatorMode: true,
credentials: {
client_email: '[email protected]',
private_key: 'fake',
},
},
}),
topics: [{ name: 'topic' }, { name: 'topic-2' }, { name: 'topic-3' }],
})
],
})
export class AppModule {}Inject the GcpPubSubClient with the topic name:
// Service
import { Injectable } from '@nestjs/common'
import { GcpPubSubClient, InjectGcpPubSubClient } from '@swang-dev/nestjs-gcp-pubsub'
@Injectable()
export class AppService {
constructor(@InjectGcpPubSubClient('topic') private readonly gcpPubSubClient: GcpPubSubClient) {}
publish(): void {
this.gcpPubSubClient.emit('hello', { message: 'Hellow world' })
}
}Server (Subscriber)
Create microservice with GcpPubSubServer:
// main
import { NestFactory } from '@nestjs/core'
import type { MicroserviceOptions } from '@nestjs/microservices'
import { GcpPubSubServer } from '@swang-dev/nestjs-gcp-pubsub'
import { AppModule } from './app.module.js'
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
strategy: new GcpPubSubServer({
prefix: 'test',
topics: [{ name: 'topic' }, { name: 'topic-2' }, { name: 'topic-3' }],
subscription: 'sub-one',
clientConfig: {
projectId: 'test-project',
apiEndpoint: 'localhost:8085',
emulatorMode: true,
credentials: {
client_email: '[email protected]',
private_key: 'fake',
},
},
}),
})
await app.listen()
}
void bootstrap()Use @EventPattern(event) to handle events:
// Controller
import { Controller } from '@nestjs/common'
import { EventPattern } from '@nestjs/microservices'
@Controller()
export class AppController {
@EventPattern('hello')
handleHello(data: unknown) {
console.log('sub', data)
}
}