Skip to content

Instantly share code, notes, and snippets.

@sketchthat
Created February 1, 2019 01:19
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/27632e1add1893ac5af814dd5fc8c522 to your computer and use it in GitHub Desktop.
Save sketchthat/27632e1add1893ac5af814dd5fc8c522 to your computer and use it in GitHub Desktop.
type ChangeDataSnapshot = functions.Change<DataSnapshot>;
type DataSnapshot = admin.database.DataSnapshot;
interface RecursiveData {
lastKey: string;
iteration: number;
records: number;
}
export const batchUpdateUser = functions.database.ref('/triggerUsers').onWrite(async (change: ChangeDataSnapshot) => {
if (!change.after.exists()) { // record removed - don't execute
return;
}
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 change.after.ref.set({
lastKey: nextKey,
iteration: iteration + 1,
records: counter + records,
});
} else {
await change.after.ref.remove();
console.log(`Finished: ${iteration} iterations, ${counter + records} records updated.`);
}
};
const data: RecursiveData = change.after.val();
if (data && data.lastKey) {
return updateUsers(data.lastKey, data.iteration, data.records);
} else {
return updateUsers();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment