Created
March 14, 2017 11:01
-
-
Save svnlto/eaeb112d8bb4664c400b50a345f6af40 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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