Search code examples
node.jsfirebase-realtime-databasegoogle-cloud-platformcrongoogle-cloud-functions

How to automate a NodeJS script in google cloud


I have a NodeJS script that fetches data from sports API. I want to execute this script every day midnight and send the data received to Firebase realtime database. Can I use Google Cloud Functions to schedule this task to run everyday? This script does not have any http urls to hit. It is just a script.

Also, can we connect firebase realtime database to a Nodejs script (not a web app) ? Because in all tutorials, they refer to connecting firebase to web app. Is this possible to do?

My idea is, the NodeJS script will run every midnight to feed data to firebase database. I will have another web app connected to firebase that will receive this data and displays to the front end. How can I achieve this using google cloud functions?

Many thanks,


Solution

  • You can use Cloud Scheduler to schedule your Cloud Functions call. When you set up your Cloud Scheduler Job, use the expression: 0 0 * * * to execute it every day at midnight.

    To call your Cloud Function, you don't need to set up a http url, you may set up it as Cloud Scheduler -> Pub Sub -> Cloud Function, this way you don't need to expose your Cloud Function public. This tutorial shows how to set it up.

    You are able to connect to firebase using Cloud Functions and the NodeJS client library, take a look at extend-with-functions.

    Some Examples taken from the official docs, similar to your use case:

    Execute intensive tasks in the cloud instead of in your app Execute intensive tasks in the cloud instead of in your app

    Notify users when something interesting happens Notify users when something interesting happens

    In your case the Function trigger would be Cloud Scheduler -> Pub Sub. Hope it helps.