@minso_minso/cloud-run-pubsub
v2.2.5
Published
Package with the boilerplate to use PubSub with Cloud Run. Is essentially a wrapper around Express.js
Downloads
6
Readme
Cloud Run PubSub
About
This is a package that receives and parses PubSub messages while deployed on Cloud Run.
It is basically a wrapper around Express.js so everything that is possible in Express is possible here too.
Usage
For the basic use case, just receiving messages and not doing anything special, following snippet is enough. Note that the handlefunction must be bound to the instance if it needs to use this
inside the function.
import { CloudRunPubsub } from '@minso_minso/cloud-run-pubsub'
const msg = new MessageHandler()
const pubsub = new CloudPubSub({
port: 5000,
handleFunc: msg.handleFunc.bind(msg),
})
pubsub.listen()
It is possible to add Sentry integration by providing Sentry.NodeOptions
to the CloudPubSub constructor as following:
const pubsub = new CloudRunPubsub({
handleFunc: async (message: Message) => console.log(message),
port: process.env.PORT || 5000,
sentrySettings: {
dsn: process.env.SENTRY_DSN,
release: process.env.VERSION || 'DEV',
},
})
The handleFunc
needs to accept a message as its single parameter (others can be added with defaults etc). Messages has the following props:
type Message = {
id: string
attributes: {
eventType: string
}
data: unknown
}
attributes can have more props but in this stage it hasnt been added.
Adding Middlewares
Since this package is a wrapper around Express.js it is possible to add middlewares to validate or modify the message on the way in. But this is before the message is parsed so the data is still a Buffer. In future versions the message parsing will be added as a middleware so that the following middlewares will have access to the parsed data.
Example:
import { CloudRunPubsub } from '@minso_minso/cloud-run-pubsub'
const mWare = (req, res, next) => {
console.log('Time:', Date.now())
next()
}
const msg = new MessageHandler()
const pubsub = new CloudPubSub({
middlewares: [mWare],
port: 5000,
handleFunc: msg.handleFunc.bind(msg),
})
pubsub.listen()