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

@luongdao/node-rabbitmq

v1.1.5

Published

NodeJS library for RabbitMQ

Downloads

31

Readme

@luongdao/node-rabbitmq

Description

A small package inpired by @golevelup/nestjs-rabbitmq library. Helps to work with rabbitmq in nodejs more easily (support expressjs).

Connection Management

This packages leverages amqp-connection-manager package to support connection resiliency.

By default, if you try to launch the app when rabbit connection is not available, an error was thrown and caused the app to crash.

If you want to enable connection resiliency, you can configure connectionInitOptions to not wait for a connection to be available. For example:

import {
  RabbitMQService,
  EXTENDED_EXCHANGE_TYPE,
} from '@luongdao/node-rabbitmq';

async function initRabbitMQ() {
  const rabbitMQService = new RabbitMQService({
    exchanges: [
      {
        name: 'exchange1',
        type: EXTENDED_EXCHANGE_TYPE.TOPIC,
      },
    ],
    uri: 'amqp://rabbitmq:rabbitmq@localhost:5672',
    connectionInitOptions: { wait: false },
  });

  await rabbitMQService.initConnection();
}

With wait set to false, unavailability of a RabbitMQ broker still allows your application to bootstrap correctly and relevant channel setups take place whenever a connection can be established.

The same principle applies to when a connection is lost. In such cases, rabbitmq tries to reconnect and set up everything again once it is reconnected.

Usage

Install

npm install ---save @luongdao/node-rabbitmq

or

yarn add @luongdao/node-rabbitmq

Module Initialization

Import and add RabbitMQService it to the imports array of module.

import {
  RabbitMQService,
  EXTENDED_EXCHANGE_TYPE,
} from '@luongdao/node-rabbitmq';

async function initRabbitMQ() {
  const rabbitMQService = new RabbitMQService({
    exchanges: [
      {
        name: 'exchange1',
        type: 'topic',
      },
    ],
    uri: 'amqp://rabbitmq:rabbitmq@localhost:5672',
    channels: {
      channel_1: {
        prefetchCount: 15,
        default: true,
      },
      channel_2: {
        prefetchCount: 2,
      },
    },
  });

  await rabbitMQService.initConnection();
}

Register RabbitMQ subscribers

Simply make use of registerSubscriber() function of the connection object obtained from your rabbitmq service.

import { RabbitMQSubscriberHandler } from '@luongdao/node-rabbitmq';

// init rabbitmq service and connection

export const subscriber1: RabbitMQSubscriberHandler<{
  data: string;
}> = (msg) => {
  logger.debug('Subscriber 1 is running: ' + msg.data);
};

await service.connection.registerSubscriber(subscriber1, {
  queue: 'queue_1',
  exchange: 'exchange_1',
  routingKey: 'routing_key_1',
  queueOptions: {
    channel: 'channel_1',
  },
});

Handling messages with format different than JSON

By default, messages are parsed with JSON.parse method when they are received and stringified with JSON.stringify on publish. If you wish to change this behavior, you can use your own parsers, like so

import {
  RabbitMQService,
  EXTENDED_EXCHANGE_TYPE,
} from '@luongdao/node-rabbitmq';
import { ConsumeMessage } from 'amqplib';

async function initRabbitMQ() {
  const rabbitMQService = new RabbitMQService({
    // ...other configs
    deserializer: (message: Buffer, msg: ConsumeMessage) => {
      const decodedMessage = myCustomDeserializer(
        msg.toString(),
        msg.properties.headers,
      );
      return decodedMessage;
    },
    serializer: (msg: any) => {
      const encodedMessage = myCustomSerializer(msg);
      return Buffer.from(encodedMessage);
    },
  });

  await rabbitMQService.initConnection();
}

Publising Messages (Fire and Forget)

If you just want to publish a message onto a RabbitMQ exchange, use the publish method of the AmqpConnection which has the following signature:

public publish<T = any>(
  exchange: string,
  routingKey: string,
  message: T,
  options?: amqplib.Options.Publish
)

// init service and connnection
await rabbitMQService.connection.publish('exchange_1', 'routing_key_1', {message: 'Hello World'})

For example:

// init service and connnection
await rabbitMQService.connection.publish('exchange_1', 'routing_key_1', {
  message: 'Hello World',
});