GCloud PubSub wrapper.
$ npm install github:squidit/sq-pubsub --save
const SqPubsub = require('sq-pubsub')
const PubSub = new SqPubsub('project-name', 'path/to/file/credentials.json')
If you wish to enable or disable the verbose logging just pass a third parameter with a boolean value:
const PubSub = new SqPubsub('project-name', 'path/to/file/credentials.json', true) // Enables verbose logging
const PubSub = new SqPubsub('project-name', 'path/to/file/credentials.json', false) // Disables verbose logging
This defaults to false
PubSub.listenMessages(SUBSCRIPTION, (message, err) => {
if (!err) {
console.log(message.data)
} else if (err) {
console.error(err)
}
})
The message
object has the following properties:
message.id
: The ID of the message.message.ackId
: ID used to acknowledge the message as received.message.data
: Message contents, which is a buffer, so it's necessary to usemessage.data.toString()
to parse the value.message.attributes
: Message atributes.message.timestamp
: Timestamp of when PubSub received the message.
This returns an instance of subscription
.
The unlisten
function removes all listeners from the subscription.
const subscription = PubSub.listenMessages(SUBSCRIPTION, (message, err) => {
if (!err) {
console.log(message.data)
} else if (err) {
console.error(err)
}
})
// Remove listeners
PubSub.unlisten(subscription)
It is rather important to mark a message as acknowledged for two reasons:
- Once the message is marked as acknowledged, it is removed from the topic queue
- A listener which has received a message (and haven't yet marked it as acknowledged) cannot receive new messages until the last message is acknowledged or the acknowledge timeout has ended.
To acknowledge a message, use the ack
function. Same thing goes when a message does not need to be acknowledged (called nack
), using the nack
function.
PubSub.listenMessages(SUBSCRIPTION, (message, err) => {
if (!err) {
console.log(message.data)
PubSub.ack(message)
} else if (err) {
console.error(err)
PubSub.nack(message)
}
})
It is also possible to use the autoAck
flag to automatically acknowledge all messages upon received:
PubSub.listenMessages(SUBSCRIPTION, cb(message, err), true) // autoAck as true (defaults to false)
PubSub can debounce the number of messages it receives at once in order to reduce the number of active processing if you need to. For this, you need only to assign a last parameter with the number of messages you want to receive at once:
PubSub.listenMessages(SUBSCRIPTION, cb(message, err), false, 5) // 5 messages at a time (defaults to 50)
We need to use the topic instead of the subscription:
PubSub.publishMessage(TOPIC, { message: 'test' })
.then((response) => console.log(response))
.catch((err) => console.error(err))