Reputation: 1780
I wrote firebase cloud function when node's specific value update then it needs to be triggered.firebase structure and code is below.i use javascript firebase cli for this.the thing is in firebase console it keep throwing Function returned undefined, expected Promise or value
Node name/Id
|--sensore1:10;
|--sensore2:20;
|--sensore3:50;
exports.pressureExceeding = functions.database.ref("Reservoir/{id}")
.onUpdate(evnt => {
console.log(evnt.after.val);
const sensData = evnt.after.val;
const status = sensData.sensor3;
console.log(evnt.after.val);
if (status > 71) {
const payLoad = {
notification: {
title: "Emergency Alert",
body: "{sensData.keys} Pressure is High",
badge: "1",
sound: "defualt"
}
};
admin.database().ref("FcmToken").once("value")
.then(allToken => {
if (allToken.val()) {
console.log("token available");
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payLoad);
} else {
console.log("no token available");
}
});
}
});
Upvotes: 0
Views: 39
Reputation: 83048
1/ You are not correctly returning the Promise returned by the once()
asynchronous method.
2/ There is also an error in the following lines:
console.log(evnt.after.val);
const sensData = evnt.after.val;
It should be:
console.log(evnt.after.val());
const sensData = evnt.after.val();
since val()
is a method
3/ Finally you should take into account the case when status <= 71.
Therefore you should adapt your code as follows:
exports.pressureExceeding = functions.database.ref("Reservoir/{id}")
.onUpdate(evnt => {
console.log(evnt.after.val);
const sensData = evnt.after.val;
const status = sensData.sensor3;
console.log(evnt.after.val);
if (status > 71) {
const payLoad = {
notification: {
title: "Emergency Alert",
body: "{sensData.keys} Pressure is High",
badge: "1",
sound: "defualt" // <- Typo
}
};
//What happens if status <= 71?? You should manage this case, as you are using payload below.
return admin.database().ref("FcmToken").once("value"). // <- Here return the promise returned by the once() method, then you chain the promises
.then(allToken => {
if (allToken.val()) {
console.log("token available");
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payLoad);
} else {
console.log("no token available");
return null; // <- Here return a value
}
});
}
});
A last remark: you are using the old syntax, for versions < 1.0. You should probably update your Cloud Function version (and adapt the syntax). Have a look at the following doc: https://firebase.google.com/docs/functions/beta-v1-diff
Upvotes: 1