Reputation: 23
I have a Cloud Functions, which triggers if a certain value in my Realtime Database changes. After that I need to read an other value from the Database.
I searched the web and found one solution. It worked: The function triggered as soon as the value at /ID/temp_id
changed, but it took additional 5 seconds to read the value at /ID/I
.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.getID = functions.database.ref("/ID/temp_id").onUpdate((change, context)=>{ //triggers the function when value "temp_id" changes
const tempID = change.after.val();
const i_snap = admin.database().ref("/ID/i").once("value", function(snapshot){ //read the value at "/ID/i" from the databse
const i = snapshot.val();
})
})
Is there any way to read the value at /ID/I
faster?
Upvotes: 2
Views: 561
Reputation: 2204
You have to trigger a function through an HTTP request by using functions.https
. This allows invoke a synchronous function.
Use functions.https
to create a function that handles HTTP events. The event handler for an HTTP function listens for the onRequest()
event.
Used as arguments for onRequest()
, the Request
object gives you access to the properties of the HTTP request sent by the client, and the Response
object gives you a way to send a response back to the client.
exports.date = functions.https.onRequest((req, res) => {
// ...
});
More details documentation: https://firebase.google.com/docs/functions/http-events
Take a look at the example below:
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//Call function via HTTP requests. This allows invoke a synchronous function
exports.showValue = functions.https.onRequest((req, res) => {
const params = req.url.split("/");
const tempId = params[2];
return admin.database().ref('ID/' + tempId).once('value', (snapshot) => {
var value = snapshot.val();
res.send(`
<!doctype html>
<html>
<head>
<title>${value.name}</title>
</head>
<body>
<h1>Title ${value. name}, id ${value.id}</h1>
</body>
</html>`
);
});
});
Upvotes: 0
Reputation: 317958
In general, you cannot simply speed up a simple database write like that. Be aware that Cloud Functions have an unavoidable cold start time for the first invocation of your function on a new server instance.
I would actually not expect your function to work at all because you're not returning a promise that resolves when all the asynchronous work is complete in your function. You're obliged to do that so that your function terminates normally.
Upvotes: 1