Installation
Before we commence, we will need to setup firebase on our local machine environment and we can easily do this by following the steps listed below:
1. Install the Firebase CLI via npm
by running the following command:
npm install -g firebase-tools
2. Sign into Firebase using your Google account by running the following command: firebase login
3. Test that the CLI is properly installed and access your account by listing your Firebase projects. Having done that, you can now run the following command: firebase projects:list
For more details about cli commands follow the below link
https://firebase.google.com/docs/cli
Initialize Firebase Functions Project
To setup firebase function project, please the below command firebase init
This command will create a firebase functions project with default files. Please follow the structure by hitting the link below
https://firebase.google.com/docs/cli#initialize_a_firebase_project
Integrate Firebase Function with Express
Once you setup the firebase function on your machine, it automatically creates an index.js inside functions folder.
The index.js file has the following default code:
const functions = require('firebase-functions'); // Create and Deploy Your First Cloud Functions// // https://firebase.google.com/docs/functions/write-firebase-functions// exports.helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase!"); });
What you have to do is customize the code so that it is compatible with firebase like the below
const functions = require("firebase-functions") const express = require("express") /* Express */ const app = express() app.get("*", (request, response) => { response.send("Hello from Express on Firebase!") }) const api = functions.https.onRequest(app) module.exports = { api }
With this code in place, we can now proceed to create multiple endpoint on the same function code.
Firebase Auth
Verify the idToken which comes after login in using firebase auth. For more details, please follow the below link : https://firebase.google.com/docs/auth/admin/verify-id-tokens#verify_id_tokens_using_the_firebase_admin_sdk
// idToken comes from the client app admin.auth().verifyIdToken(idToken) .then(function(decodedToken) { let uid = decodedToken.uid; // ... }).catch(function(error) { // Handle error })
Firestore Db Operations
Before starting db operation, there is a need to initialize the cloud firestore using the firebase server key file. Here is an example:
const admin = require('firebase-admin'); let serviceAccount = require('path/to/serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); let db = admin.firestore()
Add Data into Firestore
Cloud Firestore stores data in Documents. From here, every thing is subsequently stored in Collections. Using Cloud Firestore will create collections and documents implicitly, the very first time you add data to the document. What this means is that you do not need to explicitly create collections or documents :
Create a new collection and a document using the following example code.
// let docRef = db.collection('user').doc('{{userId}}'); // in place of {{userId}} we will put unique userId lets assume we have userId is 123 let docRef = db.collection('user').doc('123'); let setAda = await docRef.set({ first: 'Robert', last: 'Lovelace', born: 1996 });
Update data
update data is very similar to add and it is uniquely designed to allow you update users information.
let docRef = db.collection('user').doc('123'); // here if userid 123 exists then it will updated or it will create an user with id 123 let setAda = await docRef.set({ first: 'Saurabh', last: 'Kumar', born: 1996 });
Read data
To read the whole collection we will use the get method like this:
let snapshot = await db.collection('user').get(); snapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); });
To read a specific use we will use the get method in different ways. Here, checkout this example:
let snapshot = await db.collection('user').doc('123').get(); snapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); });
Firestore Db Triggers
There are 4 types of db triggers that exists on firestore events
1. onCreate
Triggered when a document is written to for the first time.
2. onUpdate
Triggered when a document already exists and has any value changed.
3. onDelete
Triggered when a document with data is deleted.
4. onWrite
Triggered when onCreate
, onUpdate
or onDelete
is triggered.
onCreate Event
This event is called whenever we add a new record of any specific document path. For instance, lets assume we have collection named user and we created a create trigger on user collection, we will have something like this.
exports.createUser = functions.firestore .document('user/{userId}') .onCreate((snap, context) => { // Get an object representing the document // e.g. {'name': 'Marie', 'age': 66 } const newValue = snap.data(); // access a particular field as you would any JS property const name = newValue.name; // perform desired operations … })
Once a document is added to user collection, this trigger will be called. With this in place, we can now do stuffs that we need to do after a user has been added to the user collection.
onUpdate Trigger
This event is called whenever we update any records, like
exports.updateUser = functions.firestore .document('user/{userId}') .onUpdate((change, context) => { // Get an object representing the document // e.g. {'name': 'Marie', 'age': 66} const newValue = change.after.data(); // …or the previous value before this update const previousValue = change.before.data(); // access a particular field as you would any JS property const name = newValue.name; // perform desired operations … });
Whenever an update is made to any records in user collection, this trigger is automatically called.
onDelete Trigger
This trigger is called when a record is removed from user collection. Below is a simple example:
exports.deleteUser = functions.firestore .document('users/{userID}') .onDelete((snap, context) => { // Get an object representing the document prior to deletion // e.g. {'name': 'Marie', 'age': 66} const deletedValue = snap.data(); // perform desired operations … })
onWrite Trigger
This trigger is activated whenever onCreate, onUpdate or onDelete trigger is called. Here, checkout an example:
exports.modifyUser = functions.firestore .document('users/{userID}') .onWrite((change, context) => { // Get an object with the current document value. // If the document does not exist, it has been deleted. const document = change.after.exists ? change.after.data() : null; // Get an object with the previous document value (for update or delete) const oldDocument = change.before.data(); // perform desired operations … });
Security Rules
Using security rules, we can restrict the user access to the database resources. For instance, lets say a user creates an account, only that user can see his/her information from db. Here is how to easily write security rules:
// Allow read/write access on all documents to any user signed in to the application service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth.uid != null; } } }
The above rule can restrict access to documents. What this entails is that only a logged in user can perform the read and write operation.
for more details in security rules follow the link
https://firebase.google.com/docs/firestore/security/get-started