Last active
March 17, 2017 09:11
-
-
Save bezysoftware/c04973eda1c41f9585f4c440f64fb508 to your computer and use it in GitHub Desktop.
Changes cloud function
This file contains hidden or 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 { Event } from 'firebase-functions'; | |
| import { DeltaSnapshot } from 'firebase-functions/lib/providers/database'; | |
| // intialize admin | |
| admin.initializeApp(functions.config().firebase); | |
| // export the function registration | |
| export let writeTransactionChange = functions | |
| .database | |
| .ref('/transactions/{groupId}/{entityId}') | |
| .onWrite(event => writeEntityChange(event, "transaction")); | |
| // functions which writes the Change to Firebase DB | |
| async function writeEntityChange(event: Event<DeltaSnapshot>, entity: String) | |
| { | |
| let entityId = event.params['entityId']; | |
| let groupId = event.params['groupId']; | |
| let action = getAction(event); // can be insert / update / delete | |
| let changesRef = event.data.ref.root.child("/changes/" + groupId); | |
| let undocumentedEvent = event as any as UndocumentedEvent; // hack to get to uid | |
| let by = undocumentedEvent.auth.variable == null ? null : undocumentedEvent.auth.variable.uid; | |
| let change: Change = | |
| { | |
| "action": action, | |
| "by": by, | |
| "entity": entity, | |
| "entityId": entityId, | |
| "serverTimestamp": admin.database.ServerValue.TIMESTAMP | |
| }; | |
| await changesRef.push().set(change); | |
| return change; | |
| } | |
| function getAction(event: Event<DeltaSnapshot>) | |
| { | |
| if (event.data.val() && !event.data.previous.val()) { | |
| return "insert"; | |
| } else if (event.data.val() && event.data.previous.val()) { | |
| return "update"; | |
| } else { | |
| return "delete"; | |
| } | |
| } | |
| interface UndocumentedEvent { | |
| auth: { | |
| variable: { | |
| uid: string | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment