Skip to content

Instantly share code, notes, and snippets.

@shadow1349
Last active September 13, 2019 22:09
Show Gist options
  • Save shadow1349/8cf08f02b469c21b409b231391fed0ad to your computer and use it in GitHub Desktop.
Save shadow1349/8cf08f02b469c21b409b231391fed0ad to your computer and use it in GitHub Desktop.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { INote, IUser } from 'firebasenoteapptypes';
export const NoteCreated = functions.firestore
.document('Notes/{NoteId}')
.onCreate((snapshot, context) => {
const note = snapshot.data() as INote;
const userRef = admin
.firestore()
.collection('Users')
.doc(note.Author);
return admin
.firestore()
.runTransaction(t =>
t.get(userRef).then(doc => {
const user = doc.data() as IUser;
return t.update(userRef, {
NumNotes: user.NumNotes + 1
});
})
)
.catch(e => console.log('TRANSACTION ERROR: ', e));
});
export const NoteDeleted = functions.firestore
.document('Notes/{NoteId}')
.onDelete((snapshot, context) => {
const note = snapshot.data() as INote;
const userRef = admin.firestore().doc(`Users/${note.Author}`);
return admin
.firestore()
.runTransaction(t =>
t.get(userRef).then(doc => {
const user = doc.data() as IUser;
return t.update(userRef, {
NumNotes: user.NumNotes - 1
});
})
)
.catch(e => console.log('TRANSACTION ERROR: ', e));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment