Created
February 1, 2019 00:29
-
-
Save sketchthat/76b3ef9db3191775e737ae5bee0d9ec5 to your computer and use it in GitHub Desktop.
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
export const batchUpdateUser = functions.database.ref('/triggerUsers').onWrite(async (_change) => { | |
const updateUsers = async (lastKey: string = '', iteration: number = 0, records: number = 0) => { | |
const snapshots: DataSnapshot = await admin.database().ref('/users') | |
.orderByKey() | |
.startAt(lastKey) | |
.limitToFirst(10) | |
.once('value'); | |
const batchUpdate = {}; | |
let nextKey = null; | |
let counter = 0; | |
snapshots.forEach(snapshot => { | |
const userId = snapshot.key; | |
if (userId !== lastKey) { | |
counter++; | |
batchUpdate[`/users/${userId}/lastProcessed`] = admin.database.ServerValue.TIMESTAMP; | |
nextKey = userId; | |
} | |
return false; | |
}); | |
await admin.database().ref('/') | |
.update(batchUpdate); | |
if (nextKey) { | |
await updateUsers(nextKey, iteration + 1, counter + records); | |
} else { | |
console.log(`Finished: ${iteration} iterations, ${counter + records} records updated.`); | |
} | |
}; | |
return updateUsers(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment