fastify-google-pubsub
v1.0.4
Published
A fastify plugin for Google pubsub integrations
Downloads
75
Maintainers
Readme
Fastify Plugin for Google Pubsub
A plugin for Fastify to use the Google Cloud Pub/Sub Client for publishing and subscribing to topics.
Install
npm install fastify-google-pubsub
Basic Usage
After registering the plugin, publish()
and subscribe()
functions are added to a pubsub
decorator on the fastify
object. The options object on the register
call needs to include all topics used by subsequent calls to publish()
or subscribe()
, or those calls with throw an error.
Single Topic Example
const pubsubClient = require('fastify-google-pubsub')
module.exports = async function(fastify, opts) {
// Register the client as a plugin
fastify.register(pubsubClient, { topics: 'topic-name']})
// Subscribe to the topic
const messageHandler = (message) => {
console.log('Received Message: ', message.data.toString())
}
const optionalCloseHandler = () => {
console.log('Subscription closed')
}
await fastify.pubsub.subscribe('topic-name', 'topic-subscription-name', messageHandler, optionalCloseHandler)
// Publish to the same topic
await fastify.pubsub.publish('topic-name', JSON.stringify({ message: 'contents' }), { attribute: 'value' })
}
Dual Topic Example
const pubsubClient = require('fastify-google-pubsub')
module.exports = async function(fastify, opts) {
// Register the client as a plugin
fastify.register(pubsubClient, { topics: ['topic-1-name', 'topic-2-name']})
// Subscribe to the first topic
const messageHandler = (message) => {
console.log('Received Message: ', message.data.toString())
}
await fastify.pubsub.subscribe('topic-1-name', 'topic-1-subscription-name', messageHandler)
// Publish to the second topic
await fastify.pubsub.publish('topic-2-name', JSON.stringify({ message: 'contents' }), { attribute: 'value' })
}