簡體   English   中英

Firebase 函數實時數據庫觸發器無法正常工作

[英]Firebase functions Realtime Database triggers not working properly

每次新用戶注冊時,我都嘗試發送通知,我當前的代碼(省略了問題不需要的代碼):

const functions = require("firebase-functions");

const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

const doctorRef = functions.database.instance("myinstance").ref("/doctors/{pushId}");

exports.newDoctorNotification = doctorRef
    .onCreate((snapshot, context) => {
      const newDoctorID = context.params.pushId;
      console.log("val: " + snapshot.val());
      console.log("key: " + snapshot.key);
      
      const notificationContent = {
        notification: {
          title: "New Doctor",
          body: "A new doctor just signed up! uid: " + newDoctorID,
          icon: "default",
          sound: "default",
        },
      };
      
      snapshot.ref.root.child("device_tokens").child("admin").get()
            .then((querySnapshot) => {
              querySnapshot.forEach((adminToken) => {
                console.log("found admin: " + adminToken.val());
                admin.messaging().sendToDevice(adminToken.val(), notificationContent)
                  .then(function(result) {
                    console.log("Notification sent");
                    return null;
                  })
                  .catch(function(error) {
                    console.log("Notification failed ", error);
                    return null;
                  });
                });
            });
      
      return true;
    });

和我當前的數據庫:

數據庫節點示例

出於某種原因,當我添加一個新節點時,根本沒有調用該函數,但是當我嘗試在整個 Google Cloud 控制台功能測試中對其進行測試時,該值顯示為 null,關鍵是“醫生”。 並且 context.params.pushId 是“未定義的”..

控制台輸出: 在此處輸入圖像描述

如果您要添加新醫生,那么我很確定doctorRef應該如下所示: const doctorRef = functions.database.ref("/doctors/{pushId}");

然后onCreate將檢測新的醫生節點。

使用您當前的代碼,您正在監聽對醫生數據屬性的添加。

如果在函數的某些代碼路徑中沒有要執行的異步工作,則可以只返回null

這是Documentation1中的原因之一,為什么事件驅動函數無法完成

當用 Node.js 編寫的函數返回被拒絕的承諾或將非空值傳遞給回調時。 然后函數默認停止執行,事件被丟棄。

根據Documentation1 ,您還需要終止后台函數並返回空值或使用其他 promise 方法。

當函數返回時,Cloud Functions 認為事件驅動函數執行完成。 如果該函數創建后台任務(例如使用線程、futures、JavaScript Promise 對象、回調或系統進程),您必須在從您的函數返回之前終止或以其他方式解決這些任務。 函數返回之前未終止的任何任務都可能無法完成,並可能導致未定義的行為。

有關更多信息,您可以參考這些thread1thread2這可能會對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM