A cheatsheet for using firebase
-
Avoiding Vendor lockin by creating wrapper function for every firebase function used
-
Use Firestore for more when you have more complex data to store and have to make less requests (< 50K requests)
-
Use Realtime Database when you have less data and have to make a lot of frequent requests (> 50K requests)
-
Copy your Firebase web app's Firebase configuration and paste in a global JS file or your index.html file
import 'firebase/auth';
There are 5 main auth functions:
With email and password
await firebase.auth().createUserWithEmailAndPassword(email, password);
await firebase.auth().signInWithEmailAndPassword(email, password);
await firebase.auth().signOut()
let unsubscribe = firebase.auth().onAuthStateChanged(callback);
// unsubscribe function clears the listener and callback function takes a user parameter
firebase.auth().currentUser;
// return user or null
Security Rules controls who can and can't read and write data into firebase databases and storage.
rules_version = '2'; // Latest version here
service <<name>> {
match <<path>> {
allow <<methods>> : if <<condition>>
}
}
rules_version = '2';
service cloud.firestore {
match /database/{database}/documents {
match /{document=**}{
allow write : if false;
allow read: if request.auth.uid !== null;
}
match /users/{userId} {
allow write: if request.auth.uid == userId;
}
}
}
{
"rules": {
"<<path>>": {
".read": <<condition>>,
".write": <<condition>>,
".validate": <<condition>>
"<<path>>": {
"<<path>>": {
".read": <<condition>>,
".write": <<condition>>
}
}
}
}
}
{
"rules": {
".read": "true",
".write": "auth!=null",
"posts": {
"$userId": {
"$postId": {
".write": true
}
}
}
}
}
Learn the Firebase Security Rules Language here.
import 'firebase/firestore';
let ref = firebase.firestore().collection(collectionName)
let doc = firebase.firestore().collection(collectionName).doc(docId)
Get the data of a document
let getData = await ref.doc(docId).get();
let data = getData.exists ? getData.data() : null;
Get all the data of a collection
let allData = await ref.get();
allData.forEach(doc => // doc.id & doc.data());
Adding data to a collection
await ref.add(data);
Setting data to a document
await ref.doc(docId).set(data);
Updating collection data
await ref.doc(docId).update(updatedData);
Deleting a document
await ref.doc(docId).delete();
Deleting a field
let removefield = ref.update({
fieldName: firebase.firestore.FieldValue.delete()
});
let queryData = await ref.where('key', 'condition', 'value').get();
queryData.forEach(doc => // doc.id & doc.data());
await ref.orderBy("field", "desc").limit(num).get();
Realtime updates of a collection
ref.onSnapshot(results => {
results.map/foreach(doc => // doc.id & doc.data())
});
Realtime updates of a document
doc.onSnapshot(doc => // doc.id & doc.data());
// ...
Type 'firebase init' and select 'Functions' and follow the required steps in the terminal
To deploy use 'firebase deploy'