1.0.0 • Published 4 years ago

nestjs-pg-pubsub v1.0.0

Weekly downloads
174
License
MIT
Repository
github
Last release
4 years ago

PG PubSub for NestJS

A simple NestJS module wrapping pg-listen.

Installation

# yarn
$ yarn add -D nestjs-pg-pubsub

# npm
$ npm i --save nestjs-pg-pubsub

Usage

First, register the module for your app (e.g. app.module.ts)

@Module({
  imports: [
    PgPubSubModule.register({
      host: '0.0.0.0',
      port: 5433,
      user: 'root',
      password: 'root',
      database: 'test',
    }),
  ],
  providers: [AppGateway, AppService],
  controllers: [AppController],
})
export class ApplicationModule {}

Inject PgSubscriber in your service, and listen in on a channel:

import { Injectable } from '@nestjs/common';
import { InjectPgSubscriber, PgSubscriber } from 'nestjs-pg-pubsub';

@Injectable()
export class FooService {
  constructor(
    @InjectPgSubscriber() private readonly pgSubscriber: PgSubscriber,
    private readonly appService: AppService,
  ) {
    // IMPORTANT - need this line to respond to events
    this.pgSubscriber.listenTo('my-channel');
    this.pgSubscriber.notifications.on('my-channel', (payload) => {
      // Do something with the payload
      // or don't! I don't care!
      console.log(payload.message, payload.timestamp);
    });
  }
}

And send a message to it from some other service/controller/thing:

@Controller()
export class BarController {
  constructor(
    @InjectPgSubscriber
    private readonly pgSubscriber: PgSubscriber,
  ) {}

  @Get('foobar')
  foobar() {
    this.pgSubscriber.notify('my-channel', {
      message: 'hallo :3',
      timestamp: Date.now(),
    });
  }
}

API

Once you've injected PgSubscriber, you can pretty much follow the API for pg-listen.

However, you don't need to .connect() / .close(), as this module takes care of that for you.

Debugging

pg-listen uses the DEBUG=pg-listen:* namespace for debugging, might be helpful!

Stay in touch

License

MIT licensed.