Test cloud functions, firestore triggers, fcm locally without need to upgrade for blaze plan 🔥

Overview

Idea

Test and try cloud functions with FCM locally and for free without upgrade to firebase blaze plan 🔥

What you will learn 🧑‍💻

  • Setup NodeJs for cloud functions development 💚
  • Test Cloud Functions loclly (without deploy and pay for blaze plan) ❤️‍🔥
  • Firestore triggers 🔥
  • Send fcm (notifications) 🔔
  • Modifiy documents on cloud function 📄
  • Read collections/documents 📖
  • Test our cloud functions with client side in my case (Flutter App) 📱

What do you need

  • Install NodeJs must be version(10,12,14,16) to support firebase cli

  • Install Java needed to start the local emulators

  • Now run this command to install Firebase CLI & tools

    npm install -g firebase-tools

Setup project

  • Before we start go to firebase console and create firebase project

  • Login to your firebase account, in cmd run

    firebase login

    If it says already logged in run this command (just to make sure your credintials are valid and you agreed to the latest firebase cli terms)

    firebase login --reauth
  • Create folder for your cloud functions project (there must be no spacebars in path) for example:

    C:\Users\USERNAME\Desktop\cloud_function_test
  • Cd to your project folder and run

    firebase init

    (follow the video)

    1.mp4
  • Now lets setup FCM things so we can test it locally (download key and paste it on your folder project)

    2.mp4

Coding

Open your functions/index.js file and remove all the code and let us start from the zero
  • Import firebase functions modules to access triggers functions & admin modules to access database(firestore) & cloud messaging

    const functions = require("firebase-functions");
    const admin = require("firebase-admin");
  • Initialize your admin sdk with your key credentail that you just download it

    // for example ("C:\\Users\\HP\\Desktop\\cloud_function_test\\key_name.json")
    const keyPath = 'key_path';
    
    admin.initializeApp(
        // TODO: remove this object when you finish and want to deploy to firebase
        { credential: admin.credential.cert(keyPath) }
    );
  • Write our first trigger function (onOrderCreated) you can name it whatever you want

    /** fire when new document added to orders collection */
    exports.onOrderCreated = functions.firestore.document('orders/{id}')
    .onCreate((change, context) => {
        /** do something here */
        return null;
    });
    // firestore have 4 triggers and they all have same syntax
    // onCreate => Fire whenever new document added
    // onUpdate => Fire when existing document modified
    // onDelete => Fire when deleting document
    // onWrite => Fire When create,update,delete document
  • Explore params (change,context) with simple example: of changing any order name that gets created and add emoje next to it

    exports.onOrderCreated = functions.firestore.document('orders/{id}')
      .onCreate((change, context) => {
          // id is identical to orders/{id} which mean if it was orders/{oId} it would be context.params.oId
          const createdDocumentId = context.params.id;
          // data of the created document
          const createdDocument = change.data();
          // access field from document, if the field doesnt exist value will be undifined
          const orderName = createdDocument.name;
          // check if the field viewTimes defined (exist)
          if(orderName){
              // modify document before saving it to firebase
              return change.ref.update({name: orderName + ' 📦'});
          }else {
              // return null means you dont want to return any promise/action its (JS) thing
              // but do i have to return null in all triggers? actully yes, bcz by default
              // it will return (undifned) and that can cause some problems!
              return null;
          }
      });
  • Lets run our code and see how far we got 🦅

    firebase emulators:start
    3.mp4
  • Other triggers have different way to get data

    /** onUpdate trigger */
    exports.onOrderUpdated = functions.firestore.document('orders/{id}')
      .onUpdate((change, context) => {
          const oldDoc = change.before.data(); // before the edit
          const updatedDoc = change.after.data(); // after the edit
          return null;
      });
    
    /** onDelete trigger */
    exports.onOrderDeleted = functions.firestore.document('orders/{id}')
      .onDelete((change, context) => {
          const deletedDoc = change.data(); // you can do backup
          return null;
      });
    
    /** onWrite trigger (fire when document update,delete,create) */
    exports.onOrderStateChange = functions.firestore.document('orders/{id}')
      .onWrite((change, context) => {
           // only has value if its (update operation) otherwise it will be undefined
          const oldDoc = change.before.exists ? change.before.data() : null;
          const newDoc = change.after.data();
          return null;
      });

FCM (send notificaitons)

  • Now after we took a quick look of how things work on cloud function lets make some actions, we will send fcm to all users collection (who have fcm_token) whenever new order is created
      exports.onOrderCreated = functions.firestore.document(`orders/{id}`)
      .onCreate(async (change, context) => {
          // *) read all users collection
          const usersRef = admin.firestore().collection('users');
          const snapshot = await usersRef.get();
          // *) hold users fcm tokens
          const usersFcmTokens = [];
          // *) loop on all users documents and check if each one has fcm token
          snapshot.forEach(doc => {
              if (doc.get('fcm_token') != null && doc.get('fcm_token').trim().length > 0) {
                  usersFcmTokens.push(doc.get('fcm_token'));
              }
          });
          // *) fcm options:
          // IMPORTANT: priority is a must because android & ios kill background process so if the priority is normal
          // or low the notification will not be shown when the app is terminated
          const options = {
              priority: "high", timeToLive: 60 * 60 * 24
          };
          // *) title,body and data that will be sent with notification
          const payload = {
              notification: {
                  title: 'Orders',
                  body: 'There is a new order!',
              }, data: {
                  'name': 'Emad Beltaje', 
                  'Note': 'Dont forget to rate repository 🌟'
              }
          };
          // *) send notifications
          if (usersFcmTokens.length > 0) {
              await admin.messaging().sendToDevice(usersFcmTokens, payload, options);
          }
          return null;
      });

lets test it with client side (in my case Flutter app)

  • first run this command to start your cloud functions emulators

    firebase emulators:start
    
  • You can use my Flutter Repo for quick start

    • Go to lib/utils/fcm_helper.dart

    • Now print the generated fcm token

      static _sendFcmTokenToServer(){
          var token = MySharedPref.getFcmToken();
          Logger().e(token); // just print the token
      }
      
    • add it to one of users in users collection (field name must be fcm_token)

    • create new order to trigger (onOrderCreated) function

You can follow the video

Video_2022-06-23_141614.mp4

Support

For support, email [email protected] or Facebook Emad Beltaje.
Dont Forget to star the repo 🌟

You might also like...

The Chat'Inn is a simple and minimal realtime chat application whose database is powered by firebase and firestore.

The Chat-in The Chat'Inn is a simple and minimal realtime chat application whose database is powered by firebase and firestore. The frontend part is c

Aug 8, 2022

Login of app to remind to drink water, using Firebase tools like Firebase Auth and Firebase Firestore

Login of app to remind to drink water, using Firebase tools like Firebase Auth and Firebase Firestore

Water Reminder Login App Menu Contents Motivation Final Images How to download the project and run it? Technologies utilized Dev 📌 Motivation This ap

Aug 22, 2022

a toy project to explore Stable Diffusion locally through a nodeJS server.

SD-explorer foreword this is a toy project to run the Stable Diffusion model locally. if you're after something more solid, I'd suggest you use WebUI

Dec 18, 2022

🤗 A CLI for running Stable Diffusion locally via a REST API on an M1/M2 MacBook

Stable Diffusion REST API A CLI for running Stable Diffusion locally via a REST API on an M1/M2 MacBook Pre-requisites An M1/M2 MacBook Homebrew Pytho

Dec 26, 2022

Concept Art/Prototyping faster with AIDA (AIDAdiffusion), "All-In-one" app for running Stable Diffusion on windows PC locally.

Concept Art/Prototyping faster with AIDA (AIDAdiffusion),

AIDAdiffusion Concept Art/Prototyping faster with ourbunka internal tool AIDA (AIDAdiffusion), "All-In-one" app for running Stable Diffusion on window

Nov 23, 2022

EL/ASI: Encrypt Locally, Account Secure Interchange

EL/ASI: Local App Security Protocol EL/ASI (Encrypt Locally, Account Secure Interchange) defines a protocol for protecting and exchanging data in loca

Dec 28, 2022

A superfast and easy to use knowledge base to help your customers get the info they need, when they need it most.

A superfast and easy to use knowledge base to help your customers get the info they need, when they need it most.

A superfast and easy to use knowledge base to help your customers get the info they need, when they need it most. helpkb is an open-source Next.js (A

Dec 5, 2022

MerLoc is a live AWS Lambda function development and debugging tool. MerLoc allows you to run AWS Lambda functions on your local while they are still part of a flow in the AWS cloud remote.

MerLoc is a live AWS Lambda function development and debugging tool. MerLoc allows you to run AWS Lambda functions on your local while they are still part of a flow in the AWS cloud remote.

MerLoc MerLoc is a live AWS Lambda function development and debugging tool. MerLoc allows you to run AWS Lambda functions on your local while they are

Dec 21, 2022

Collection of Rowy's templates for cloud functions cod snippets - including for derivative, action columns and extensions.

Collection of Rowy's templates for cloud functions cod snippets - including for derivative, action columns and extensions.

Rowy Templates Collection of Rowy's backend templates and code snippets for cloud functions - including for derivative, action columns and extensions.

Nov 16, 2022
Owner
Emad Beltaje
Emad Beltaje
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A lightweight jQuery custom scrollbar plugin, that triggers event when reached the defined point.

Scrollbox A lightweight jQuery custom scrollbar plugin, that triggers event when reached the defined point. Demo Page Table of contents Browser compat

null 15 Jul 22, 2022
A Blaze apostas é um cassino online que recentemente se tornou popular nas redes sociais.

Blaze Double ?? Bot Blaze A Blaze apostas é um cassino online que recentemente se tornou popular nas redes sociais. Esse bot tem como objetivo enviar

Jocimar Costa 58 Dec 29, 2022
esse bot envia sinais, do gamer double blaze, direto para chats do telegram. leave the star ⭐️

Bot Blaze Double A blaze.com, site de aposta online, operada pela empresa Prolific Trade N.V. e bastante popular nas mídias sociais. Em um de seus jog

Elizandro Dantas 42 Dec 30, 2022
The Plan: Equator

The Plan: Equator Most people overestimate what they can do in one year and underestimate what they can do in ten years. See ?? what I'm going to do i

ZhengHe 1 Jan 7, 2022
The project is a To-Do list project to help plan daily, weekly or monthly activity. I used Html, CSS and JavaScript Technology to execute the project.

<<<<<<< HEAD To Do List This project is geared towards applying acguired skills for development of my porfolio through the following practices: Create

Victor Efosa Osagie 6 Dec 19, 2022
This is ongoing project and it will has plan for several co-workers and friends.

MERN: Full-stack Chat Application Introduction The MERN stack which consists of Mongo DB, Express.js, Node.js, and React.js is a popular stack for bui

RainBow 6 Dec 3, 2022
Aplicação Angular CRUD para uso e prática do Firebase com Authentication, Firestore e Storage

DiariosApp This project was generated with Angular CLI version 13.3.3. Development server Run ng serve for a dev server. Navigate to http://localhost:

José Almir 4 Jun 3, 2022