all files / src/ subscriber.js

100% Statements 130/130
98.25% Branches 56/57
100% Functions 14/14
100% Lines 39/39
8 statements, 8 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76        11× 11×                       12× 12×                         13× 13×                      
'use strict';
const amqp = require('amqplib');
const _ = require('lodash');
const util = require('util');
 
let log;
 
export default class Subscriber {
    constructor(options = {}, logOptions) {
        log = require('logfilename')(__filename, logOptions);
        if(!options.exchange){
            throw new Error('exchange parameter missing in options');
        }
        if(!options.queueName){
            throw new Error('queueName parameter missing in options');
        }
        this._queue;
        this._channel;
        this._options = _.defaults(options, {
            type: 'topic',
            url: 'amqp://localhost'
        });
        log.info('Subscriber options:', util.inspect(this._options));
    }
 
    async start(onIncomingMessage) {
        log.info('start');
 
        let options = this._options;
        let connection = await amqp.connect(options.url);
        log.info('createChannel');
        this._channel = await connection.createChannel();
        log.info('assertExchange ', options.exchange);
        await this._channel.assertExchange(options.exchange, options.type, { durable: true });
        log.info('assertQueue name: ', options.queueName);
        let result = await this._channel.assertQueue(options.queueName, { exclusive: false });
 
        this._queue = result.queue;
        let routingKeys = options.routingKeys || [options.queueName];
        log.info('assertQueue keys ', routingKeys);
        for(let routingKey of routingKeys){
            log.info('bindQueue routingKey ', routingKey);
            await this._channel.bindQueue(this._queue, options.exchange, routingKey);
        }
 
        log.info('prefetch and consume');
        this._channel.prefetch(1);
        await this._channel.consume(this._queue, onIncomingMessage.bind(this));
        log.info('started');
    }
    async stop() {
        log.info('stop');
        if (this._channel) {
            return await this._channel.close();
        } else {
            log.warn('stopping but channel was not opened');
        }
    }
    ack(message) {
        log.debug('ack');
        this._channel.ack(message);
    }
    nack(message) {
        log.debug('nack');
        this._channel.nack(message);
    }
    async purgeQueue() {
        log.info('purgeQueue ', this._queue);
        if (this._channel) {
            return await this._channel.purgeQueue(this._queue);
        } else {
            log.warn('purgeQueue: channel not opened');
        }
    }
}