Last active
September 16, 2019 21:22
-
-
Save shadow1349/1a02b29432b9a933444aff1e26f85913 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, NoteModel } from "firebasenoteapptypes"; | |
import { AlgoliaSearch } from "../algolia"; | |
const index = new AlgoliaSearch("Notes"); | |
export const NoteCreated = functions.firestore | |
.document("Notes/{NoteId}") | |
.onCreate(async (snapshot, context) => { | |
const note = snapshot.data() as INote; | |
await index.store(new NoteModel(note)); | |
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.set( | |
userRef, | |
{ | |
NumNotes: user.NumNotes + 1 | |
}, | |
{ merge: true } | |
); | |
}) | |
) | |
.catch(e => console.log("TRANSACTION ERROR: ", e)); | |
}); | |
function diffTags(params: { before?: string[]; after?: string[] }) { | |
if (params.before && params.after) { | |
if (params.before.length !== params.after.length) { | |
return true; | |
} | |
let isDifferent = false; | |
const a = params.after.sort(); | |
const b = params.before.sort(); | |
for (let i = 0; i < a.length; i++) { | |
if (a[i] !== b[i]) { | |
isDifferent = true; | |
break; | |
} | |
} | |
return isDifferent; | |
} else { | |
return true; | |
} | |
} | |
export const NoteUpdated = functions.firestore | |
.document("Notes/{NoteId}") | |
.onUpdate(async (change, context) => { | |
const before = change.before.data() as INote; | |
const after = change.after.data() as INote; | |
if ( | |
before.Title !== after.Title || | |
before.Note !== after.Note || | |
diffTags({ before: before.Tags, after: after.Tags }) | |
) { | |
await index.store(new NoteModel(after)); | |
} | |
return Promise.resolve(null); | |
}); | |
export const NoteDeleted = functions.firestore | |
.document("Notes/{NoteId}") | |
.onDelete(async (snapshot, context) => { | |
const note = snapshot.data() as INote; | |
await index.delete(context.params.NoteId); | |
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