-
Notifications
You must be signed in to change notification settings - Fork 0
/
publish.js
39 lines (34 loc) · 1.11 KB
/
publish.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
const getClient = require('./getClient')
/**
* Publish a message to a topic using the given client.
*
* @param {object} client - The client to publish with.
* @param {string} topic - The topic to publish on.
* @param {*} payload - String or object payload, converted as required.
* @returns {Promise} Promise that resolves on success or rejects on error.
*/
const publishMessage = (client, topic, payload) => new Promise((resolve, reject) => {
const data = typeof payload === 'object' ? JSON.stringify(payload) : payload
client.publish(topic, data, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
/**
* Publish an update to a topic.
*
* @param {*} payload - String or object payload, converted as required.
* @param {object} [options] - Optional options.
* @returns {Promise} Promise that resolves on success or rejects on error.
*/
const publish = function (payload, options = {}) {
if (!payload) {
throw new Error('Payload is missing.')
}
return getClient(this.scope, options)
.then(client => publishMessage(client, this.path, payload))
}
module.exports = publish