0

我在节点的特定值更新时编写了firebase云函数,然后需要触发它。firebase结构和代码如下。我为此使用javascript firebase cli。事情在firebase控制台中它不断抛出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");
       }
     });
   }
});
4

1 回答 1

1

1/ 您没有正确返回once()异步方法返回的 Promise。

2/ 以下几行也有错误:

  console.log(evnt.after.val);
  const sensData = evnt.after.val;

它应该是:

  console.log(evnt.after.val());
  const sensData = evnt.after.val();

因为val()是一种方法

3/最后你应该考虑status <= 71的情况。

因此,您应该按如下方式调整您的代码:

 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
       }
     });
   }
});

最后一点:您使用的是旧语法,版本 < 1.0。您可能应该更新您的 Cloud Function 版本(并调整语法)。查看以下文档:https ://firebase.google.com/docs/functions/beta-v1-diff

于 2019-03-17T11:39:41.077 回答