Last active
September 13, 2019 22:09
-
-
Save shadow1349/8cf08f02b469c21b409b231391fed0ad to your computer and use it in GitHub Desktop.
This file contains 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
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