Skip to content

Instantly share code, notes, and snippets.

@sketchthat
Created February 1, 2019 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchthat/76b3ef9db3191775e737ae5bee0d9ec5 to your computer and use it in GitHub Desktop.
Save sketchthat/76b3ef9db3191775e737ae5bee0d9ec5 to your computer and use it in GitHub Desktop.
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