K41F4r
K41F4r

Reputation: 1551

AMQP + NodeJS wait for channel

I have a service in FeathersJS that initiates a connection to RabbitMQ, the issue is how to await for a channel to be ready before receiving requests:

class Service {
  constructor({ amqpConnection, queueName }) {
    this.amqpConnection = amqpConnection;
    this.queueName = queueName;
    this.replyQueueName = queueName + "Reply"
  }

  async create(data, params) {
    new Promise(resolve => {
      if (!this.channel) await this.createChannel();
      channel.responseEmitter.once(correlationId, resolve);
      channel.sendToQueue(this.queueName, Buffer.from(data), {
        correlationId: asyncLocalStorage.getStore(),
        replyTo: this.replyQueueName,
      });
    });
  }

  async createChannel() {
    let connection = this.amqpConnection();
    let channel = await connection.createChannel();

    await channel.assertQueue(this.queueName, {
      durable: false,
    });

    this.channel = channel;
    channel.responseEmitter = new EventEmitter();
    channel.responseEmitter.setMaxListeners(0);
    channel.consume(
      this.replyQueueName,
      (msg) => {
        channel.responseEmitter.emit(
          msg.properties.correlationId,
          msg.content.toString("utf8")
        );
      },
      { noAck: true }
    );
  }
  ....
}

Waiting for the channel to be created during a request seems like a waste. How should this be done "correctly"?

Upvotes: 0

Views: 1062

Answers (1)

Daff
Daff

Reputation: 44215

Feathers services can implement a setup method which will be called when the server is started (or you call app.setup() yourself):

class Service {
  async setup () {
    await this.createChannel();
  }
}

Upvotes: 1

Related Questions