Code coverage report for src/subscriber.js

Statements: 100% (99 / 99)      Branches: 100% (39 / 39)      Functions: 100% (14 / 14)      Lines: 100% (36 / 36)      Ignored: 2 statements, 4 branches     

All files » src/ » subscriber.js
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  1 1 1   1     1 10 10 2   8 1   7 7 7       7       5   5 5 5 5 5   5 5 5 5   5 5   5     6       1       12 12     2 2     6       1        
'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: 'direct',
            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 });
        log.info('assertQueue res ', result);
        this._queue = result.queue;
        await this._channel.bindQueue(this._queue, options.exchange, options.key);
        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');
        }
    }
}