UNPKG

andresusandi-pubsub

Version:

PubSub library that provides a number of different underlying technologies

62 lines (52 loc) 3.22 kB
const { PubSub } = require('@google-cloud/pubsub'); const { name: packageName } = require('./package.json'); class GooglePubSubBase { constructor(projectId, keyFilename, topicName, subscriptionName) { if (!projectId) throw new Error("projectId is required"); if (!keyFilename) throw new Error("keyFilename is required"); if (!topicName) throw new Error("topicName is required"); if (!subscriptionName) throw new Error("subscriptionName is required"); this.projectId = projectId; this.keyFilename = keyFilename; this.topicName = topicName; this.subscriptionName = subscriptionName; // const me = this; // console.log(`${packageName}/${me.constructor.name} Initiailizng PubSub for project ${projectId} using authetication file ${keyFilename}`); // me.pubSubClient = new PubSub({ projectId, keyFilename }); // console.log(`${packageName}/${me.constructor.name} Creating new topic named ${topicName}`); // me.pubSubClient.createTopic(topicName, (o) => { // console.log(`${packageName}/${me.constructor.name} Topic creation result code: `, o.code); // me.topic = me.pubSubClient.topic(topicName); // console.log(`${packageName}/${me.constructor.name} Creating new subscription named ${subscriptionName}`); // me.pubSubClient.createSubscription(topicName, subscriptionName, (o) => { // console.log(`${packageName}/${me.constructor.name} Subscription creation result code: `, o.code); // me.subscription = me.pubSubClient.subscription(subscriptionName); // }); // }); } async init() { console.log(`${packageName}/${this.constructor.name} Initiailizng PubSub for project ${this.projectId} using authetication file ${this.keyFilename}`); this.pubSubClient = new PubSub({ projectId: this.projectId, keyFilename: this.keyFilename }); console.log(`${packageName}/${this.constructor.name} Creating new topic named ${this.topicName}`); try { const topicResult = await this.pubSubClient.createTopic(this.topicName); console.log(`${packageName}/${this.constructor.name} Topic creation result code: `, topicResult.code); } catch { console.log(`${packageName}/${this.constructor.name} Expected exception for topic ${this.topicName}`); } this.topic = this.pubSubClient.topic(this.topicName); console.log(`${packageName}/${this.constructor.name} Creating new subscription named ${this.subscriptionName}`); try { const subscriptionResult = await this.pubSubClient.createSubscription(this.topicName, this.subscriptionName); console.log(`${packageName}/${this.constructor.name} Subscription creation result code: `, subscriptionResult.code); } catch { console.log(`${packageName}/${this.constructor.name} Expected exception for subscription ${this.subscriptionName}`); } this.subscription = this.pubSubClient.subscription(this.subscriptionName); } } module.exports = GooglePubSubBase;