Reputation: 35
firebase-cloud-function noob here.
I'm struggling in trying to to read a database value from a https firebase cloud function.
For example putting this https://us-central1-database-daa11.cloudfunctions.net/test?deviceID=DEV-14SfJ6
in the browser should return a web page showing lmvBlnf9dhXvbc8SuOD3it
I have following database structure:
{
"devices" : {
"DEV-14SfJ6" : {
"mode" : "die_hard",
"registred" : "true",
"user" : "lmvBlnf9dhXvbc8SuOD3it"
},
"DEV-3Xrcwr" : {
"mode" : "die_hard",
"registred" : "true"
"user" : "lmvBlnf9dhXvbc8SuOD3it"
}
}
and I have deploy the following test function to read the user parameter for a device. For example DEV-14SfJ6.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
//
//
//
exports.test = functions.https.onRequest((request, response) => {
var db = admin.database();
const deviceID = request.query.deviceID;
console.log("Sent device ID", deviceID);
response.send("test ok");
var val2;
db.ref("/devices/" + deviceID + "/user").once("value").then(snap => {
val2 = snap.val();
response.statusCode(200).send(val2);
console.log(val2)
return db.ref("/devices/" + deviceID + "/user").set(val1+1);
}).catch(err => {
console.log(err);
response.send("error occurred");
});
});
but as you would expect nothing good happens. Thanks for your help.
Upvotes: 1
Views: 734
Reputation: 6354
Your function has several problems.
First, val1
is never actually defined. It's not clear what you're trying to do by setting the /devices/DEVICEID/user
(a string in the original data) to val1 + 1
.
Second, statusCode
isn't a function, you want status(200)
(or just omit it, 200 is the default).
But the real problem you have is the general handling of the function semantics and promises.
For http/https functions, the function terminates once you call response.send()
.
So, you want to make sure your database update happens before you do that. Moreover, your function calls send
twice -- once before it accesses the database, and then once after the first call to the database (and once in the catch).
Fixing will look something like this, but since it isn't clear what you are trying to do, I can't give exact code:
exports.test = functions.https.onRequest((request, response) => {
var db = admin.database();
const deviceID = request.query.deviceID;
console.log("Sent device ID", deviceID);
var val2;
db.ref("/devices/" + deviceID + "/user").once("value").then(snap => {
val2 = snap.val();
console.log(val2)
return db.ref("/devices/" + deviceID + "/user").set('some new value');
}).then(() => {
response.status(200).send(val2);
}).catch(err => {
console.log(err);
response.send("error occurred");
});
Upvotes: 3