Last active
March 22, 2021 17:54
-
-
Save dulimarta/82281eddf94b2dec857ee1e5db960583 to your computer and use it in GitHub Desktop.
Cloud Firestore Snippets
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 { | |
FirebaseFirestore, | |
DocumentReference, | |
CollectionReference, | |
GeoPoint, | |
} from "@firebase/firestore-types"; | |
const stateData = [ | |
{ name: "Alaska", abbrev: "AK", capital: "Juneau", population: 735_720 }, | |
{ | |
name: "Alabama", | |
abbrev: "AL", | |
capital: "Montgomery", | |
population: 4_934_190, | |
}, | |
{ | |
name: "Michigan", | |
abbrev: "MI", | |
capital: "Lansing", | |
population: 9_992_430, | |
}, | |
]; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const stateColl: CollectionReference = db.collection("states"); | |
/* Add a single document */ | |
const task1 = stateColl | |
.doc("FL") | |
.set({ name: "Florida", population: 21_944_600, capital: "Tallahassee" }) | |
.then(() => { | |
console.log("Inserted new doc with user provided ID"); | |
}); | |
/* Add multiple records from an array */ | |
const task2 = stateData.map((s: any) => | |
stateColl | |
.doc(s.abbrev) | |
.set({ | |
name: s.name, | |
population: s.population, | |
capital: s.capital, | |
}) | |
.then(() => { | |
console.log("Inserted new doc with user provided ID"); | |
}) | |
); | |
return Promise.all([task1, ...task2]).then(() => Promise.resolve()); | |
} |
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 { | |
FirebaseFirestore, | |
DocumentReference, | |
CollectionReference, | |
} from "@firebase/firestore-types"; | |
// Needed for GeoPoint class | |
import firebase from "firebase"; | |
const parks = [ | |
{ name: "Arches", location: "Utah", lat: 38.68, lon: -109.57 }, | |
{ | |
name: "Black Canyon of Gunnison", | |
location: "Colorado", | |
lat: 38.57, | |
lon: -107.72, | |
}, | |
{ | |
name: "Crater Lake", | |
location: "Oregon", | |
lat: 42.94, | |
lon: -122.1, | |
}, | |
]; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const parkColl: CollectionReference = db.collection("parks"); | |
const task = parks.map((p: any) => { | |
const coord = new firebase.firestore.GeoPoint(p.lat, p.lon); | |
return parkColl | |
.add({ name: p.name, location: p.location, geoPos: coord }) | |
.then((doc: DocumentReference) => { | |
console.log("New park added with ID", doc.id); | |
}); | |
}); | |
return Promise.all(task).then(() => Promise.resolve()); | |
} |
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 { | |
FirebaseFirestore, | |
CollectionReference, | |
} from "@firebase/firestore-types"; | |
import firebase from "firebase/app"; | |
const michganCities = [ | |
{ | |
name: "Albion", | |
lat: 42.2478, | |
lon: -84.7591, | |
}, | |
{ | |
name: "Byron Center", | |
lat: 42.8117, | |
lon: -85.7278, | |
}, | |
{ | |
name: "Grand Rapids", | |
lat: 42.9611, | |
lon: -85.6555, | |
}, | |
]; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const cityColl: CollectionReference = db | |
.collection("states") | |
.doc("MI") | |
.collection("cities"); | |
/* Add multiple records from an array */ | |
michganCities.forEach(async (z: any) => { | |
const coord = new firebase.firestore.GeoPoint(z.lat, z.lon); | |
await cityColl.add({ | |
name: z.name, | |
geoPos: coord, | |
}); | |
}); | |
console.log("Cities added as a subcollection of MI"); | |
return Promise.resolve(); | |
} |
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 { | |
CollectionReference, | |
FirebaseFirestore, | |
QueryDocumentSnapshot, | |
QuerySnapshot, | |
} from "@firebase/firestore-types"; | |
export default async function (db: FirebaseFirestore): Promise<void> { | |
const stColl: CollectionReference = db.collection("states"); | |
return stColl.get().then((q: QuerySnapshot) => { | |
// console.log("Query is", q); | |
q.forEach((ds: QueryDocumentSnapshot) => { | |
console.log(`Doc ID`, ds.id); | |
const { population, name } = ds.data(); | |
console.log(`Population of ${name} is ${population}`); | |
}); | |
}); | |
} |
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 { | |
DocumentReference, | |
DocumentSnapshot, | |
FirebaseFirestore, | |
} from "@firebase/firestore-types"; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const mich: DocumentReference = db.doc("states/MI"); | |
return mich.get().then((mdoc: DocumentSnapshot) => { | |
if (mdoc.exists) { | |
console.log("Doc", mdoc.data()); | |
const dd = mdoc.data()!; | |
console.log("========================"); | |
// Use JS/TS object destructure to extract some of the fields | |
const { population, capital } = dd; | |
console.log(`Capital of-----`, mdoc.id, "is", capital); | |
console.log(`Population of---- ${mdoc.id} is ${population}`); | |
} | |
}); | |
} |
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 { | |
DocumentReference, | |
FirebaseFirestore, | |
} from "@firebase/firestore-types"; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const mich: DocumentReference = db.doc("states/MI"); | |
const t1 = mich.update({ governor: "G. Whitmer" }).then(() => { | |
console.log("Document", mich.id, "updated"); | |
}); | |
const t2 = mich | |
.update({ governor: { name: "G. Whitmer", age: 54 } }) | |
.then(() => { | |
console.log("Document", mich.id, "updated"); | |
}); | |
return Promise.all([t1, t2]).then(() => Promise.resolve()); | |
} |
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 { | |
DocumentReference, | |
FirebaseFirestore, | |
} from "@firebase/firestore-types"; | |
import firebase from "firebase/app"; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const mich: DocumentReference = db.doc("states/MI"); | |
return mich.update({ universities: ["MSU", "UMich", "GVSU"] }).then(() => { | |
console.log("Document", mich.id, "updated"); | |
}); | |
// return mich | |
// .update({ | |
// universities: firebase.firestore.FieldValue.arrayUnion( | |
// "CMU", | |
// "Calvin", | |
// "XYZ" | |
// ), | |
// }) | |
// .then(() => { | |
// console.log("Document", mich.id, "updated"); | |
// }); | |
// return mich | |
// .update({ | |
// universities: firebase.firestore.FieldValue.arrayRemove("XYZ"), | |
// }) | |
// .then(() => { | |
// console.log("Document", mich.id, "updated"); | |
// }); | |
} |
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 { | |
DocumentReference, | |
FirebaseFirestore, | |
} from "@firebase/firestore-types"; | |
import firebase from "firebase/app"; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const mich: DocumentReference = db.doc("states/MI"); | |
return mich | |
.update({ | |
population: firebase.firestore.FieldValue.increment(3000), | |
}) | |
.then(() => { | |
console.log("Document", mich.id, "updated"); | |
}); | |
} |
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 { FirebaseFirestore } from "@firebase/firestore-types"; | |
import firebase from "firebase/app"; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const t1 = db | |
.doc("states/MI") | |
.update({ | |
governor: firebase.firestore.FieldValue.delete(), | |
}) | |
.then(() => { | |
console.log("Field deleted"); | |
}); | |
const t2 = db | |
.doc("states/AK") | |
.delete() | |
.then(() => { | |
console.log("Document Alaska removed"); | |
}); | |
return Promise.all([t1, t2]).then(() => Promise.resolve()); | |
} |
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 { | |
DocumentReference, | |
FirebaseFirestore, | |
QueryDocumentSnapshot, | |
QuerySnapshot, | |
} from "@firebase/firestore-types"; | |
import firebase from "firebase/app"; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const cityColl = db.collection("states/MI/cities"); | |
const t1 = cityColl.get().then((q: QuerySnapshot) => { | |
q.forEach(async (qd: QueryDocumentSnapshot) => { | |
const city: DocumentReference = cityColl.doc(qd.id); | |
await city.delete(); | |
}); | |
console.log("City subcollections removed"); | |
}); | |
const t2 = ["states", "parks"].map((coll: string) => { | |
const myColl = db.collection(coll); | |
myColl.get().then((q: QuerySnapshot) => { | |
q.forEach(async (qd: QueryDocumentSnapshot) => { | |
const doc: DocumentReference = myColl.doc(qd.id); | |
await doc.delete(); | |
console.log("Document ", doc.id, "removed"); | |
}); | |
console.log(`${coll} collections removed`); | |
}); | |
}); | |
return Promise.all([t1, ...t2]).then(() => Promise.resolve()); | |
} |
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 { | |
FirebaseFirestore, | |
QueryDocumentSnapshot, | |
QuerySnapshot, | |
} from "@firebase/firestore-types"; | |
export default function (db: FirebaseFirestore): Promise<void> { | |
const stateColl = db.collection("states"); | |
const q1 = stateColl | |
.where("population", "<", 5_000_000) | |
.where("population", ">", 1_000_000) | |
.get() | |
.then((qr: QuerySnapshot) => { | |
qr.forEach((qd: QueryDocumentSnapshot) => { | |
console.log("Popul < 5 million", qd.data()); | |
}); | |
}); | |
const q2 = stateColl | |
.orderBy("name") | |
.orderBy("population", "desc") | |
.get() | |
.then((qr: QuerySnapshot) => { | |
qr.forEach((qd: QueryDocumentSnapshot) => { | |
const { name, population } = qd.data(); | |
console.log("Sorted by descending population", name, population); | |
}); | |
}); | |
return Promise.all([q1, q2]).then(); | |
} |
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 { | |
DocumentChange, | |
DocumentSnapshot, | |
FirebaseFirestore, | |
QueryDocumentSnapshot, | |
QuerySnapshot, | |
} from "@firebase/firestore-types"; | |
import { LocalTime } from "@js-joda/core"; | |
export default function (db: FirebaseFirestore) { | |
db.doc("states/MI").onSnapshot((ds: DocumentSnapshot) => { | |
const time = LocalTime.now(); | |
console.log("At", time.toString()); | |
console.log( | |
"MI doc has changed", | |
ds.data(), | |
"Pending write? ", | |
ds.metadata.hasPendingWrites, | |
"from cache?", | |
ds.metadata.fromCache | |
); | |
}); | |
db.collection("states").onSnapshot((qs: QuerySnapshot) => { | |
const time = LocalTime.now(); | |
console.log("At", time.toString()); | |
// qs.forEach((qds: QueryDocumentSnapshot) => { | |
// console.log(`${qds.id} updated`, qds.data(), qds.metadata); | |
// }); | |
qs.docChanges().forEach((ch: DocumentChange) => { | |
console.log(ch.doc.id, ch.type, ch.doc.data()); | |
}); | |
}); | |
} |
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 firebase from "firebase/app"; | |
import { UserCredential } from "@firebase/auth-types"; | |
type FAuth = firebase.auth.Auth; | |
export default function (auth: FAuth): Promise<void> { | |
return auth | |
.createUserWithEmailAndPassword("dulimarh@mail.gvsu.edu", "1q2w3e4r5") | |
.then((cred: UserCredential) => { | |
console.log( | |
"New account for ", | |
cred.user?.email, | |
"with uid", | |
cred.user?.uid | |
); | |
if (cred.user?.emailVerified) | |
console.log("Email address ", cred.user?.email, " is verified"); | |
else { | |
cred.user?.sendEmailVerification(); | |
console.log("Verification email has been sent to", cred.user?.email); | |
auth.signOut(); | |
} | |
}) | |
.catch((err: any) => { | |
console.error("Oops", err); | |
}); | |
} |
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 firebase from "firebase/app"; | |
import { UserCredential } from "@firebase/auth-types"; | |
type FAuth = firebase.auth.Auth; | |
export default function (auth: FAuth): Promise<void> { | |
// This can only be done in a browser | |
const provider = new firebase.auth.GoogleAuthProvider(); | |
return auth | |
.signInWithEmailAndPassword("dulimarh@mail.gvsu.edu", "1q2w3e4r5") | |
.then((cred: UserCredential) => { | |
if (cred.user?.emailVerified) | |
console.log("Signed in", cred.user?.email, "with uid", cred.user?.uid); | |
else { | |
console.log("Your email", cred.user?.email, "has not been verified"); | |
auth.signOut(); | |
} | |
}) | |
.catch((err: any) => { | |
console.error("Oops", err, err.code); | |
}); | |
} |
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 firebase from "firebase/app"; | |
import { UserCredential } from "@firebase/auth-types"; | |
type FAuth = firebase.auth.Auth; | |
export default function (auth: FAuth): Promise<void> { | |
// This can only be done in a browser | |
const provider: firebase.auth.AuthProvider = new firebase.auth.GoogleAuthProvider(); | |
firebase.auth; | |
return auth | |
.signInWithPopup(provider) | |
.then((cred: UserCredential) => { | |
console.log("Signed in", cred.user?.email, "with uid", cred.user?.uid); | |
}) | |
.catch((err: any) => { | |
console.error("Oops", err); | |
}); | |
} |
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 firebase from "firebase/app"; | |
import { UserCredential, User } from "@firebase/auth-types"; | |
type FAuth = firebase.auth.Auth; | |
export default function (auth: FAuth): Promise<void> { | |
let currentUser: User | null = null; | |
return new Promise((resolve, reject) => { | |
let handle = auth.onAuthStateChanged((u: User | null) => { | |
console.log("From listener: user is email is", u?.email); | |
// return new Promise((res, rej) => {}); | |
if (u != null) { | |
currentUser = u; | |
} else { | |
if (currentUser != null) { | |
currentUser = null; | |
resolve(); | |
} else { | |
setTimeout(() => resolve(), 10_000); | |
} | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment