How to deploy cloud functions using Firebase CLI
August 29, 2021
1 min

How to deploy cloud functions using Firebase CLI

As per the google says, cloud functions is,

Google Cloud Functions is a serverless execution environment for building and connecting cloud services. With Cloud Functions you write simple, single-purpose functions that are attached to events emitted from your cloud infrastructure and services. Your function is triggered when an event being watched is fired. Your code executes in a fully managed environment. There is no need to provision any infrastructure or worry about managing any servers.

If you want to know more things about cloud functions. please check here.

In this article will explain you how to use Firebase CLI to deploy a cloud function.

First of all you have to install Firebase CLI to your machine. It’s available as npm module. so you need to have node.js.

npm install -g firebase-tools

Note : - If you get permission error, please use above code with sudo and the enter your password

After installing, run below code.

firebase login

Then browser open and ask you to login your Firebase account with your mail. after login, open your VS code and write following code in terminal.

firebase init

Then answered asking questions.

Note : -In here they asked what feature do you want to, then select features that you want with Space hitting and then hit Enter to confirm your choice

After that you can see linked Firebase projects to your logged account. So then you can choose correct project that you want to include this cloud function.

Then they asked for Firebase rules, Firebase indexes, type of language, ESLint, finally to install dependencies,

You can choose answers as per your wish.

After that you have successful project that can write cloud functions. Check index.js file.

I am going to add here code that I used to build presence system with Cloud Firestore as my cloud function. you can add your cloud function in index.js file.

const functions = require('firebase-functions');  
const admin = require('firebase-admin');  
admin.initializeApp();  

// Since this code will be running in the Cloud Functions environment  
// we call initialize Firestore without any arguments because it  
// detects authentication from the environment.  
const firestore = admin.firestore();  

// Create a new function which is triggered on changes to /status/{uid}  
// Note: This is a Realtime Database trigger, *not* Firestore.  
exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate( 
    async (change, context)  =>  {      
        // Get the data written to Realtime Database  
    
        const eventStatus = change.after.val();
      
        // Then use other event data to create a reference to the  
        // corresponding Firestore document.
      
        const userStatusFirestoreRef = firestore.doc(`status/${context.params.uid}`);

        // It is likely that the Realtime Database change that triggered  
        // this event has already been overwritten by a fast change in  
        // online / offline status, so we'll re-read the current data  
        // and compare the timestamps. 
 
        const statusSnapshot = await change.after.ref.once('value');  
        const status = statusSnapshot.val(); 
        functions.logger.log(status, eventStatus);
      
        // If the current timestamp for this data is newer than  
        // the data that triggered this event, we exit this function.  
        
        if  (status.last_changed > eventStatus.last_changed)  {  
            return  null;  
        }
 
        // Otherwise, we convert the last_changed field to a Date
            
        eventStatus.last_changed =  new  Date(eventStatus.last_changed);
          
        // ... and write it to Firestore.  
        return userStatusFirestoreRef.set(eventStatus);  
    });

Now you have can deploy this cloud functions by

firebase deploy --only functions

Congratulations ! Now you have completely deploy your cloud function.


Tags

firebasefirestorecloud functionsbuild presencedeployfirebase CLI