Skip to content

Instantly share code, notes, and snippets.

@heygambo
Last active February 9, 2019 12:34
Show Gist options
  • Save heygambo/e8a70fb8175f900ce27959cc2abe0c96 to your computer and use it in GitHub Desktop.
Save heygambo/e8a70fb8175f900ce27959cc2abe0c96 to your computer and use it in GitHub Desktop.
Assure the firebase function is only being processed once if invoked multiple times.
import { CollectionReference } from "@google-cloud/firestore"
const wait = (seconds: number): Promise<void> => new Promise(resolve => setTimeout(resolve, seconds * 1000))
export interface CreateThisOneTimeOptions {
collectionRef: CollectionReference,
}
export interface ThisOneTimeOptions {
docKey: string,
}
export interface ThisOneTimeOperations {
ensure: (options: ThisOneTimeOptions) => Promise<boolean>
}
export function createThisOneTime ({ collectionRef }: CreateThisOneTimeOptions): ThisOneTimeOperations {
return {
ensure: ({ docKey }: ThisOneTimeOptions): Promise<boolean> => {
const createdAt = Date.now()
const random = collectionRef.doc().id
const doc = collectionRef.doc(docKey)
return new Promise(async resolve => {
await collectionRef.firestore.runTransaction(async t => {
const snapshot = await t.get(doc)
if (!snapshot.exists) {
t.set(doc, { createdAt, random })
}
})
await wait(0.1)
const snapshot = await doc.get()
const exists = snapshot.exists
const sameTimestamp = exists && snapshot.data()!.createdAt === createdAt
const sameRandomness = exists && snapshot.data()!.random === random
return resolve(sameTimestamp && sameRandomness)
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment