all files / src/ publisher.js

100% Statements 79/79
100% Branches 33/33
100% Functions 12/12
100% Lines 22/22
2 statements, 6 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                                        15×                        
'use strict';
const Promise = require('bluebird');
const amqp = require('amqplib');
const _ = require('lodash');
const util = require('util');
 
let log;
 
export default class Publisher {
    constructor(options = {}, logOptions) {
        log = require('logfilename')(__filename, logOptions);
        if(!options.exchange){
            throw new Error('exchange parameter missing in options');
        }
        this._options = _.defaults(options, {
            type: 'topic',
            url: 'amqp://localhost'
        });
        log.info('Publisher options:', util.inspect(this._options));
    }
    async start() {
        let options = this._options;
        log.info('start ', util.inspect(options));
        let connection = await amqp.connect(options.url);
        log.info('connected to mq');
        this._channel = await connection.createChannel();
        log.info('connected to channel');
        let res = await this._channel.assertExchange(options.exchange, options.type, { durable: true });
        log.info('connected ', res);
    }
 
    async stop() {
        log.info('stop');
        if (this._channel) {
            return await this._channel.close();
        } else {
            return Promise.resolve();
        }
    }
    async publish(key, message) {
        log.info('publish exchange:%s, key:%s, message ', this._options.exchange, key, message);
        if(this._channel){
            return this._channel.publish(this._options.exchange, key, new Buffer(message));
        } else {
            throw {
                code: 503,
                name: "MessageQueueNotAvailable",
                message: "Message queue channel not available"
            };
        }
    }
}