Skip to content

Instantly share code, notes, and snippets.

@ddikman
Created March 22, 2021 10:52
Show Gist options
  • Save ddikman/1e82c0f8709bf694a6fc73e221cc48d0 to your computer and use it in GitHub Desktop.
Save ddikman/1e82c0f8709bf694a6fc73e221cc48d0 to your computer and use it in GitHub Desktop.
firebase-function-example.ts
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
interface AuthorData {
role: string;
name: string;
}
const onAuthorNameUpdated = functions.firestore.document('users/{userId}').onWrite(async (change, context) => {
if (!change.after.exists) {
// skip
return
}
const data = change.after.data() as AuthorData;
const previous = change.before.data() as AuthorData;
// skip non-authors
if (data.role !== 'author' && data.role !== 'admin') {
return;
}
// skip if no name update
if (previous.name === data.name) {
return;
}
console.log(`Author '${previous.name}' changed name to '${data.name}', updating all articles`);
const snapshot = await admin.firestore().collection('articles')
.where('authorId', '==', change.after.id)
.get();
const updates = snapshot.docs.map((doc) => admin.firestore().doc(`articles/${doc.id}`).update({'author': data.name }))
await Promise.all(updates)
console.log(`Updated ${updates.length} articles!`)
})
export = onAuthorNameUpdated;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment