graphql-amqp-subscriptions
Version:
GraphQL AMQP Subscriptions
72 lines • 2.71 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AMQPSubscriber = void 0;
const common_1 = require("./common");
class AMQPSubscriber {
logger;
connection;
exchange;
queue;
channelPromise = null;
constructor(config, logger) {
this.logger = logger;
this.connection = config.connection;
this.exchange = {
name: 'graphql_subscriptions',
type: 'topic',
options: {
durable: false,
autoDelete: false
},
...config.exchange
};
this.queue = {
options: {
exclusive: true,
durable: false,
autoDelete: true
},
...config.queue
};
}
async subscribe(routingKey, action, arguments_, options) {
// Create and bind queue
const channel = await this.getOrCreateChannel();
await channel.assertExchange(this.exchange.name, this.exchange.type, this.exchange.options);
const queue = await channel.assertQueue(this.queue.name ?? '', this.queue.options);
await channel.bindQueue(queue.queue, this.exchange.name, routingKey, arguments_);
// Listen for messages
const options_ = await channel.consume(queue.queue, (message) => {
const content = common_1.Common.convertMessage(message);
this.logger('Message arrived from Queue "%s" (%j)', queue.queue, content);
action(routingKey, content, message);
}, { noAck: true, ...options });
this.logger('Subscribed to Queue "%s" (%s)', queue.queue, options_.consumerTag);
// Dispose callback
return async () => {
this.logger('Disposing Subscriber to Queue "%s" (%s)', queue.queue, options_.consumerTag);
const ch = await this.getOrCreateChannel();
await ch.cancel(options_.consumerTag);
if (this.queue.unbindOnDispose) {
await ch.unbindQueue(queue.queue, this.exchange.name, routingKey);
}
if (this.queue.deleteOnDispose) {
await ch.deleteQueue(queue.queue);
}
};
}
async getOrCreateChannel() {
if (!this.channelPromise) {
this.channelPromise = this.connection.createChannel()
.then(channel => {
channel.on('error', (error) => {
this.logger('Publisher channel error: "%j"', error);
});
return channel;
});
}
return this.channelPromise;
}
}
exports.AMQPSubscriber = AMQPSubscriber;
//# sourceMappingURL=subscriber.js.map