Prince Gupta
Prince Gupta

Reputation: 1

Exported Channel Becomes Undefined on Second Use

I'm working with RabbitMQ in a Node.js application and have created a class that manages the connection and channel. The class exports the channel, and it works fine the first time I use it. However, when I try to reuse the same channel in another function, I get the following error:

Error while starting the worker ReferenceError: rabbitMqInstance is not defined
    at dbWorker (file:///D:/Projects/Practice_2/Notification-system/src/worker/db.worker.js:4:21)
    at file:///D:/Projects/Practice_2/Notification-system/src/worker/db.worker.js:25:1
    at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)

RabbitMq Connection

class RabbitMq {
  constructor() {
    this.connection;
    this.channel;
  }

  async connect() {
    try {
      this.connection = await amqp.connect(process.env.RABBITMQ_URL);
      this.channel = await this.connection.createChannel();
      console.log("connected to rabbitMQ successfully");
    } catch (error) {
      console.log("something went wrong while connection to rabbitMq", error);
      process.exit(1);
    }
  }

  getChannel() {
    if (!this.channel) {
      throw new Error("RabbitMq is not connected");
    }
    return this.channel;
  }
}

export const rabbitMqInstance = new RabbitMq();

Worker

const channel = rabbitMqInstance.getChannel();
    channel.assertQueue("db-queue");
    channel.consume("db-queue", (msg) => {
      console.log(msg.content.toString());
    });
    channel.ack(msg);

    // const connection = await amqp.connect(process.env.RABBITMQ_URL);
    // const channel = await connection.createChannel();

    channel.assertQueue("db-queue", { durable: true });

    channel.consume("db-queue", (msg) => {
      console.log(msg.content.toString());
      channel.ack(msg);
    });

Upvotes: 0

Views: 20

Answers (0)

Related Questions