Skip to content

Instantly share code, notes, and snippets.

@svnlto
Created March 14, 2017 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save svnlto/eaeb112d8bb4664c400b50a345f6af40 to your computer and use it in GitHub Desktop.
Save svnlto/eaeb112d8bb4664c400b50a345f6af40 to your computer and use it in GitHub Desktop.
const mqlight = require('mqlight');
const joi = require('joi');
const url = require('url');
const debug = require('debug')('mqService');
module.exports = (cfg) => {
const { protocol, hostname, port } = cfg.endpoint.mq;
const baseURL = url.format({
slashes: true,
protocol,
hostname,
port
});
const opts = Object.assign({}, { service: baseURL });
const client = mqlight.createClient(opts);
const wrapper = {
send: (topic, data, opts) => {
joi.validate(topic, joi.string(), (err) => {
if (!err) {
debug('send', topic, data, opts);
client.send(topic, data, opts);
}
});
},
subscribe: (topic, share, opts) => {
joi.validate(topic, joi.string(), (err) => {
if (!err) {
debug('subscribe', topic, share, opts);
client.subscribe(topic, share, opts);
}
});
},
unsubscribe: (topic, share, opts) => {
joi.validate(topic, joi.string(), (err) => {
if (!err) {
debug('unsubscribe', topic, share, opts);
client.unsubscribe(topic, share, opts);
}
});
},
stop: client.stop(),
id: client.id,
service: client.service,
state: client.state
};
return new Promise((resolve, reject) => {
client.on('started', () => resolve(wrapper));
client.on('message', msg => debug('mq: ', msg));
client.on('error', err => reject(err));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment