1

I have a script in Reactjs that get data (numbers) from api and addup this numbers with numbers from Firebase collection when user opens the page and the user can see this numbers. There are going to be many users in the app and every user is going to have diffrent numbers from the same script

I was wondering if its possible with Firebase Cloud Functions to run this Client side script on the server and do the callculations of this numbers on the server and store this numbers in a Firestore collection.

im a begginer in nodejs and cloud functions i dont know if this is possible to do

get the numbers from Api

  getLatestNum = (sym) => {
    return API.getMarketBatch(sym).then((data) => {
      return data;
    });
  };

Cloud function i was trying

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.resetAppointmentTimes = functions.pubsub
  .schedule('30 20 * * *')
  .onRun((context) => {
    const appointmentTimesCollectionRef = db.collection('data');
    return appointmentTimesCollectionRef
      .get() 
      .then((querySnapshot) => {
        if (querySnapshot.empty) {
          return null;
        } else {
          let batch = db.batch();
          querySnapshot.forEach((doc) => {
            console.log(doc);
          });
          return batch.commit();
        }
      })
      .catch((error) => {
        console.log(error);
        return null;
      });
  });
2
  • We would need more details on what is the getMarketBatch API. How do you call it? a simple call to a REST API HTTP endpoint? Commented Jun 29, 2020 at 7:51
  • Yes it's a simple call to a Rest API and I get a response Commented Jun 29, 2020 at 12:46

1 Answer 1

1

It is indeed possible to call a REST API from a Cloud Function. You need to use a Node.js library which returns Promises, like axios.

It's not 100% clear, in your question, to which specific Firestore doc(s) you want to write, but I make the asumption it will be done within the batched write.

So, something along the following lines should do the trick:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');

admin.initializeApp();
const db = admin.firestore();

exports.resetAppointmentTimes = functions.pubsub
.schedule('30 20 * * *')
.onRun((context) => {
    
    let apiData;
    return axios.get('https://yourapiuri...')
        .then(response => {
            apiData = response.data;  //For example, it depends on what the API returns
            const appointmentTimesCollectionRef = db.collection('data');
            return appointmentTimesCollectionRef.get();           
        })
        .then((querySnapshot) => {
            if (querySnapshot.empty) {
                return null;
            } else {
                let batch = db.batch();
                querySnapshot.forEach((doc) => {
                    batch.update(doc.ref, { fieldApiData: apiData});
                });
                return batch.commit();
            }
        })
        .catch((error) => {
            console.log(error);
            return null;
        });
});

Two things to note:

  1. If you want to add the API result to some fields value, you need to give more details on your exact need
  2. Important: You need to be on the "Blaze" pricing plan. As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)
Sign up to request clarification or add additional context in comments.

6 Comments

thank you for the info. Is it possible to call my React script like axios.get('/index.js') the api call is just a small part of the overal script i got it was to big to post in the question
Sorry but I don't understand your last comment. Can you possibly adapt your question with detailed explanations, maybe with a flow diagram.
i want to call my React script name index.js from firebase hosting. can i do this in cloud functions. Sorry for all this questions
Sorry but I don't understand. What is index.js (a React file or the Cloud Function file)? Where it is located? what do you exactly mean by "calling index.js FROM firebase hosting"??
index.js is React file. Location is from where my files go after firebase deploy(i dont know the path sorry). "calling index.js FROM firebase hosting" => firebase hosting where my files go after i do firebase deploy in terminal. I hope this helps
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.