Created
July 25, 2019 14:58
-
-
Save charroch/eb2e99b57877bddf561113bc5a9252ee to your computer and use it in GitHub Desktop.
Poor man pubsub firebase function emulator
This file contains 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
import { PubSub } from '@google-cloud/pubsub' | |
import * as a from './index' | |
import { CloudFunction } from 'firebase-functions' | |
import { Message } from '@google-cloud/pubsub' | |
import * as dotenv from 'dotenv' | |
dotenv.config() | |
const pubsub = new PubSub({ | |
projectId: process.env.GCLOUD_PROJECT | |
}) | |
console.info(`[pubsub] Starting pubsub server for receiving messages`) | |
const run = async () => { | |
for (let key in a) { | |
let value = a[key] | |
if ( | |
value.__trigger.eventTrigger && | |
value.__trigger.eventTrigger.eventType && | |
'google.pubsub.topic.publish' === value.__trigger.eventTrigger.eventType | |
) { | |
const topicName = value.__trigger.eventTrigger.resource.split('/')[3] | |
if (!topicName) { | |
continue | |
} | |
const topic = pubsub.topic(topicName) | |
const topicInst = await topic | |
.get() | |
.then(t => Promise.resolve(t[0])) | |
.catch(e => topic.create().then(t => t[0])) | |
const subscription = await topicInst | |
.createSubscription(`${key}-${topicName}`) | |
.then(t => Promise.resolve(t[0])) | |
.catch(e => pubsub.subscription(`${key}-${topicName}`)) | |
const runFunction = key => (f: CloudFunction<Message>) => async ( | |
msg: Message | |
) => { | |
console.info(`i functions: Beginning execution of ${key}`) | |
try { | |
await f.run(msg, { eventId: 'eid' }) | |
msg.ack() | |
console.info(`i functions: Finished execution of ${key}`) | |
} catch (err) { | |
console.error(`e functions: Errors in execution of ${key}: ${err}`) | |
} | |
} | |
console.info(`✔ functions Registering ${key} with ${subscription.name}`) | |
subscription.on(`message`, runFunction(key)(value)) | |
} | |
} | |
} | |
run() | |
.then(() => console.info(`✔ pubsub server running and awaiting message`)) | |
.catch(console.error) |
.env file
FIREBASE_CONFIG =
GCLOUD_PROJECT =
GOOGLE_APPLICATION_CREDENTIALS=
FIRESTORE_EMULATOR_HOST =
GOOGLE_CLOUD_PROJECT= ```
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
start the emulator first
gcloud beta emulators pubsub --verbosity=none --quiet start