Skip to content

Commit

Permalink
bulk delete RTDB
Browse files Browse the repository at this point in the history
  • Loading branch information
swantzter committed Jul 20, 2023
1 parent 825ab6e commit 6283048
Showing 1 changed file with 39 additions and 12 deletions.
51 changes: 39 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as admin from 'firebase-admin'
import { pubsub } from 'firebase-functions'
import getDeletionRoutineFunction from 'graphql-firebase-subscriptions/firebase-function'
// import getDeletionRoutineFunction from 'graphql-firebase-subscriptions/firebase-function'
admin.initializeApp()

export enum RsEvents {
Expand All @@ -10,20 +10,47 @@ export enum RsEvents {
SCORESHEET_CHANGED = 'SCORESHEET_CHANGED'
}

export const pubSubDeletionRoutine = getDeletionRoutineFunction({
topics: RsEvents
export const pubSubDeletionRoutine = pubsub.schedule('every 10 minutes').onRun(async () => {
try {
const db = admin.database()
const baseRef = db.ref('/graphql-firebase-subscriptions')
const topics = Object.values(RsEvents)

for (const topic of topics) {
const ref = baseRef.child(topic.toString())
const toDelete = await ref
.orderByChild('timestamp')
.endAt(Date.now() - (10 * 60 * 1000))
.get()

if (toDelete.exists()) {
const data = toDelete.val()
await ref.update(Object.fromEntries(Object.entries(data).map(k => [k, null])))
}
}
} catch (err) {
console.error(err)
}
})

// export const pubSubDeletionRoutine = getDeletionRoutineFunction({
// topics: RsEvents
// })

export const deviceShareDeletionRoutine = pubsub.schedule('every 1 hours').onRun(async () => {
const db = admin.firestore()
const query = db.collection('device-stream-shares')
.where('expiresAt', '<', admin.firestore.Timestamp.now())
.orderBy('expiresAt')
.limit(100)

return new Promise<void>((resolve, reject) => {
deleteQueryBatch(db, query, resolve).catch(reject)
})
try {
const db = admin.firestore()
const query = db.collection('device-stream-shares')
.where('expiresAt', '<', admin.firestore.Timestamp.now())
.orderBy('expiresAt')
.limit(100)

return new Promise<void>((resolve, reject) => {
deleteQueryBatch(db, query, resolve).catch(reject)
})
} catch (err) {
console.error(err)
}
})

async function deleteQueryBatch (db: admin.firestore.Firestore, query: admin.firestore.Query, resolve: () => void) {
Expand Down

0 comments on commit 6283048

Please sign in to comment.