-1

How can I use a Cloud function to change realtime data in my firebase database every-time the function is called? I have a data cell called Points and I want to change the value of Points into a random number between 1 and 10 every time the function is deployed. I am really new to using firebase so I wouldn't know where to really start. I have looked most of the documentation provided but none of them helped. I have tried a few things but failed miserably. Please help

Thank you,

This is what I tried...

exports.userVerification = functions.database.ref('Points')

var ref = database().ref('Points')

var number = (Math.floor(Math.random() * 10) + 1)*10

ref.update(number)
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Yraw
  • 97
  • 10
  • You say you want the data to change when the cloud function is called, but the first line of the code you have there is from the example for calling a function when the data is changed -- exactly the opposite. You should start by [reading the documentation](https://firebase.google.com/docs/functions/http-events) for writing a function that is called via HTTP requests. – Herohtar May 01 '19 at 21:16
  • I want to use Pubsub instead of HTTP – Yraw May 02 '19 at 01:10
  • In that case, [these docs](https://cloud.google.com/functions/docs/calling/pubsub) or [this tutorial](https://cloud.google.com/functions/docs/tutorials/pubsub) should be a place to look. – Herohtar May 02 '19 at 01:35

1 Answers1

1

You will find in the documentation all the details on how to trigger a Cloud Function via Pub/Sub.

You will also find a very simple "Hello World" example in the official Cloud Functions sample: https://github.com/firebase/functions-samples/tree/master/quickstarts/pubsub-helloworld

Your Cloud Function would then look like the following:

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

exports.randomNbr = functions.pubsub.topic('topic-name').onPublish((message) => {

      var ref = admin.database().ref();

      var number = Math.floor(Math.random() * (10)) + 1;

      return ref.update({ Points: number });

});

Note that we return the Promise returned by the update() asynchronous method, in order to indicate to the platform that the work is finished. I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/

Note also that you cannot simply do ref.update(number);: you'll get an error (Error: Reference.update failed: First argument must be an object containing the children to replace.)

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121