Home > Back-end >  How to create a calculated field in Firebase?
How to create a calculated field in Firebase?

Time:11-14

I'm creating a Firebase application and I want to store the subscription details of users in it. I'm planning to store the start_date, end_date, and number_of_days_left for the subscription. I want to calculate number_of_days_left based on the difference between end_date and current_date. The number_of_days_left should update every day in the Firebase. What's the best possible way to do it?

CodePudding user response:

To achieve that, I recommend you to use Cloud Scheduler:

Cloud Scheduler is a fully managed enterprise-grade cron job scheduler.

So you can create a cron to update that difference daily. In that way, you'll always have a field that will contain the exact number of days left.

CodePudding user response:

To achieve the desired task you can use Scheduled Firebase Cloud Functions. This function creates a Pub/Sub topic and uses Cloud Scheduler to trigger events on that topic which ensures that the function runs on the desired schedule.

To store start_date, end_date and number_of_days_left of the subscription you can use Cloud Firestore.

First you can create a users collection in Firestore. And add a unique document when a user subscribes to the application. In the document you can store the start_date, end_date with the field of type timestamp and number_of_days_left with type number.

The Firestore database structure will look like the following -

users------>
    user1------>
        start_date
        end_date
        number_of_days_left
    user2----->
        start_date
        end_date
        number_of_days_left
    user3----->
        start_date
        end_date
        number_of_days_left

Now you can implement the scheduled Firebase Function and update the number_of_days_left field everyday. The scheduled Firebase Function uses Unix Crontab. You can find more about Unix Crontab syntax here. The following scheduled Firebase Function, which is in NodeJS, runs at 00:00 everyday and updates the number_of_days_left field for every user inside the users collection.

const admin = require("firebase-admin");
const functions = require("firebase-functions");
admin.initializeApp();
const db=admin.firestore();
exports.scheduledFunctionCrontab = functions.pubsub.schedule("0 0 * * *")
   .timeZone("Asia/Kolkata")
   // Users can choose timezone - default is America/Los_Angeles
   .onRun(async (context) => {
     const docRef = await db.collection("users").get();
     docRef.forEach((doc)=>{
       const data=doc.data();
       const difference=Math.
           floor((data.end_date-admin.firestore.Timestamp.now())/(24*60*60));
       doc.ref.update({"number_of_days_left": difference});
     });
   });

In the Function code you can specify any valid timezone of your choice which is listed here.

  • Related