How To Push New Data Into Firebase Realtime Database Using Cloud Functions?
Solution 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.
)
Post a Comment for "How To Push New Data Into Firebase Realtime Database Using Cloud Functions?"