{"size": 1569, "ext": "js", "max_stars_repo_path": "src/infrastructure/messaging/nsqMessageBus.js", "max_stars_repo_name": "brunofurmon/job-scheduler", "max_stars_repo_stars_event_min_datetime": "2021-04-05T19:53:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T17:53:22.000Z", "max_issues_repo_path": "src/infrastructure/messaging/nsqMessageBus.js", "max_issues_repo_name": "brunofurmon/job-scheduler", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/infrastructure/messaging/nsqMessageBus.js", "max_forks_repo_name": "brunofurmon/job-scheduler", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 6, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.0517241379, "max_line_length": 91, "alphanum_fraction": 0.5143403442}
const inspect = require('util');
const { Writer, Reader } = require('nsqjs');

module.exports = ({ logger }) => {
    const { NSQ_WRITER_ADDR, NSQ_READER_ADDR } = process.env;

    const writer = () => {
        const writerOptions = {
            deflate: true,
            snappy: false
        };

        const [writerHost, writerPort] = NSQ_WRITER_ADDR.split(':');
        const nsqWriter = new Writer(writerHost, writerPort, writerOptions);

        if (!nsqWriter.connected) {
            nsqWriter.connect();
        }

        nsqWriter
            .on('ready', () => {
                logger.debug('NSQ writer connection is ready');
            })
            .on('error', error => {
                logger.error('NSQ writer connection had an error', {
                    error: inspect.inspect(error)
                });
            })
            .on('closed', () => {
                logger.info('NSQ writer connection is closed');
            });

        return nsqWriter;
    };

    const reader = (topic, channel) => {
        const readerOptions = {
            deflate: true,
            snappy: false,
            lookupdHTTPAddresses: NSQ_READER_ADDR,
            clientId: `${process.env.npm_package_name}/${process.env.npm_package_version}`,
            maxInFlight: 1,
            messageTimeout: 6e4,
            maxAttempts: 3
        };

        const internalReader = new Reader(topic, channel, readerOptions);
        internalReader.connect();

        return internalReader;
    };

    return {
        reader,
        writer
    };
};
