Created
May 14, 2022 06:39
-
-
Save Saad-ISAA/915f7b95cdd1b4615dbfc346bf922e4d to your computer and use it in GitHub Desktop.
GCP PubSub Helper Library
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 { PubSub } = require('@google-cloud/pubsub'); | |
function psInit() { | |
const projectId = process.env['GCP_PROJECT']; | |
// Instantiates a client | |
const pubsub = new PubSub({ projectId }); | |
return pubsub; | |
} | |
async function psPublish(pubsub, topic, data) { | |
try { | |
const messageId = await pubsub.topic(topic).publishMessage({ json: data }); | |
console.log(`Message ${messageId} published.`); | |
} catch (error) { | |
console.error(`Received error while publishing: ${error.message}`); | |
process.exitCode = 1; | |
} | |
} | |
function psSubscribe(pubsub, subscriptionTopic, ifAck, messageFunc) { | |
const subscriptionName = subscriptionTopic; | |
const maxInProgress = 1; // configure this as user needs | |
// Instantiates a client | |
const subscriberOptions = { | |
flowControl: { | |
maxMessages: maxInProgress, | |
}, | |
}; | |
// References an existing subscription. | |
// Note that flow control settings are not persistent across subscribers. | |
const subscription = pubsub.subscription( | |
subscriptionName, | |
subscriberOptions | |
); | |
console.log( | |
`Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.` | |
); | |
subscription.on('message', messageFunc); | |
return `subscribed to ${subscriptionTo}`; | |
} | |
module.exports = { | |
psInit, | |
psPublish, | |
psSubscribe, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment