Skip to content

Instantly share code, notes, and snippets.

@hermanbanken
Forked from Crashcodebug/index.js
Last active June 2, 2022 11:35
Show Gist options
  • Save hermanbanken/c165e0c4213a52e1a924d84c0d33981d to your computer and use it in GitHub Desktop.
Save hermanbanken/c165e0c4213a52e1a924d84c0d33981d to your computer and use it in GitHub Desktop.
import * as functions from "firebase-functions" // The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
import { Firestore } from "@google-cloud/firestore"; // Cloud Firestore: Node.js Client
import * as admin from "firebase-admin"; // The Firebase Admin SDK to access Firestore.
admin.initializeApp();
const db = admin.firestore();
const adminUSA = new Firestore({projectId:"firestoreusa"}); // Firebase USA access account
const collections = ["bridges", "users", "tokens"];
collections.forEach((collection) => {
exports["create_"+collection] = functions
.region('europe-west1')
.firestore
.document(collection+'/{id}')
.onCreate(onCreate)
exports["update_"+collection] = functions
.region('europe-west1')
.firestore
.document(collection+'/{id}')
.onUpdate(onUpdate);
exports["delete_"+collection] = functions
.region('europe-west1')
.firestore
.document(collection+'/{id}')
.onDelete(onDelete);
exports["delete_"+collection] = functions
.region('europe-west1')
.firestore
.document(collection+'/{id}')
.onWrite(onWrite);
})
async function onCreate(snap: functions.firestore.QueryDocumentSnapshot) {
console.log('onCreate', snap.ref.path, snap.data());
await adminUSA.doc(snap.ref.path).set(snap.data());
}
async function onUpdate({ before, after}: { before: functions.firestore.QueryDocumentSnapshot, after: functions.firestore.QueryDocumentSnapshot}) {
console.log('upUser', before.ref.path, after.ref.path);
if (before.ref.path === after.ref.path) {
// same path, different values
await adminUSA.doc(after.ref.path).set(after.data());
} else {
// moved
await adminUSA.doc(before.ref.path).delete();
await adminUSA.doc(after.ref.path).set(after.data());
}
}
async function onDelete(snap: functions.firestore.QueryDocumentSnapshot) {
console.log('onDelete', snap.ref);
await adminUSA.doc(snap.ref.path).delete();
}
async function onWrite(change: functions.Change<functions.firestore.DocumentSnapshot>) {
console.log('onWrite', change.before, change.after);
// QUESTION how do Deletes look?
// QUESTION how do Inserts look?
}
{
"name": "firestore-test",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"author": "",
"license": "ISC",
"dependencies": {
"@google-cloud/firestore": "^5.0.2",
"firebase-admin": "^10.2.0",
"firebase-functions": "^3.21.2",
"typescript": "^4.7.2"
}
}
{
"compilerOptions": {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment