npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mkfyi/nestjs-rmq

v1.4.3

Published

A decent NestJS module for a more advanced communication between microservices using the full power of RabbitMQ

Downloads

14

Readme

Description

This package provides a more advanced communication between microservices using the full power of RabbitMQ.

Core library features

  • Separate server/client components
  • Allowing multiple connections to one or more RabbitMQ server
  • Just implement the QueueHandler interface and mark the class with one of the following decorators
    1. @Listener() - Basic consumer, the simplest thing that does something
    2. @Worker() - Work Queues, distributing tasks among workers
    3. @PubSub() - Publish/Subscribe, sending messages to many consumers at once
    4. @Routing() - Routing, receiving messages selectively
    5. @Topics() - Topics, receiving messages based on a pattern
    6. @Rpc() - RPC, Request/reply pattern
  • Optional validation of message content using class-validator
  • Lightweight wrapper of the amqplib for the Nest ecosystem

Installation

nest-rmq must be integrated into the ecosystem of Nest, so your application must require @nestjs/common and @nestjs/core. You can replace all npm commands with the package manager of your choice. So if you would like to use yarn, replace npm with yarn.

# from official npm registry
$ npm i --save @mkfyi/nestjs-rmq

# using yarn
$ yarn add @mkfyi/nestjs-rmq

# from GitHub package registry
$ npm i --save --registry=https://npm.pkg.github.com @mkfyi/nestjs-rmq

# from GitHub package registry using yarn
$ yarn add --registry=https://npm.pkg.github.com @mkfyi/nestjs-rmq

Since nest-rmq is built on top of amqplib you also need to install the types for it.

$ npm install -D @types/amqplib

Usage

Import the RabbitMQModule from @mkfyi/nestjs-rmq and call the forRoot() method inside the imports of your application module. You can also set a custom name for the connection, otherwise default will be used.

Initialization

import { RabbitMQModule } from '@mkfyi/nestjs-rmq';

@Module({
  imports: [
    // ...
    RabbitMQModule.forRoot({
      connection: {
        hostname: '',
        username: '',
        password: '',
      },
    }),
  ],
})
export class AppModule {}

If you prefer to use environment variables, consider adding the @nestjs/config and use forRootAsync() method instead.

@Module({
  imports: [
    // ...
    RabbitMQModule.forRootAsync({
      connection: {
        imports: [ConfigModule],
        useFactory: (config: ConfigService) => ({
          hostname: config.get('AMQP_HOSTNAME'),
          username: config.get('AMQP_USERNAME'),
          password: config.get('AMQP_PASSWORD'),
        }),
        inject: [ConfigService],
      },
    }),
  ],
})
export class AppModule {}
Multiple connections

You can also create multiple connections, just pass the object as above into an array and add the name property. This name is being used for the QueueHandler and QueueAdapter.

@Module({
  imports: [
    // ...
    RabbitMQModule.forRootAsync({
      connection: [
        {
          name: 'default',
          imports: [ConfigModule],
          useFactory: (config: ConfigService) => ({
            hostname: config.get('AMQP_HOSTNAME'),
            username: config.get('AMQP_USERNAME'),
            password: config.get('AMQP_PASSWORD'),
          }),
          inject: [ConfigService],
        },
        {
          name: 'stage',
          imports: [ConfigModule],
          useFactory: (config: ConfigService) => ({
            hostname: config.get('AMQP_STAGE_HOSTNAME'),
            username: config.get('AMQP_STAGE_USERNAME'),
            password: config.get('AMQP_STAGE_PASSWORD'),
          }),
          inject: [ConfigService],
        }
      ],
    }),
  ],
})
export class AppModule {}
Adapters (client)

You have to configure the adapters properts in order send messages to the respective queue.

@Module({
  imports: [
    // ...
    RabbitMQModule.forRootAsync({
      connection: {
        name: 'default',
        imports: [ConfigModule],
        useFactory: (config: ConfigService) => ({
          hostname: config.get('AMQP_HOSTNAME'),
          username: config.get('AMQP_USERNAME'),
          password: config.get('AMQP_PASSWORD'),
        }),
        inject: [ConfigService],
      },
      adapters: [
        {
          name: 'BACKEND_SERVICE',
          queue: 'example.worker,
          type: QueueAdapterType.Worker,
          connection: 'default',
        },
      ],
    }),
  ],
})
export class AppModule {}

The example shown above creates an adapter named BACKEND_SERVICE for the default connection. The value of the name property can be injected as QueueAdapter using @Inject(). You may want to change to RpcQueueAdapter for this type.

@Injectable()
export class MyService {
  public constructor(
    @Inject('BACKEND_SERVICE')
    private readonly worker: QueueAdapter,
  ) {}

  public notifyUsernameUpdate(id: string, name: string) {
    return this.worker.send({ id, name });
  }
}
Handlers (server)

Every custom queue handler has to implement the QueueHandler interface. As for the adapters, there is a separate interface for RPC based handlers called RpcQueueHandler.

@Worker({ queue: 'example.worker' })
export class ExampleWorkerQueueHandler implements QueueHandler {
  public async execute(msg: Message): Promise<void> {
    console.log(msg.object());
  }
}

Don't forget to add your queue handlers to the application module providers.

@Module({
  imports: [
    // ...
    RabbitMQModule.forRootAsync({
      // ...
    }),
  ],
  providers: [
    // ...
    ExampleWorkerQueueHandler,
  ],
})
export class AppModule {}

License

nest-rmq is MIT licensed.