【问题标题】:Making automated notifications with Firebase Cloud Functions, Messaging,Firestore使用 Firebase Cloud Functions、Messaging、Firestore 制作自动通知
【发布时间】:2019-10-06 05:25:29
【问题描述】:

我一直在尝试使用 .onUpdate() 触发器推送通知,但它不起作用。我不确定出了什么问题,因为我在 docs 上找到的任何东西几乎都没用,而且这是我第一次使用 Node.js。

我想在提交订单后使用 Firebase Cloud Functions 更新任何产品(在 Firebase 实时数据库中)时通知用户(使用 Firebase 消息传递),并且要求产品库存

集合的结构是这样的: products (collection) -> {productID} (document) -> attributes: {name, barcode, price, stock, sold}

    //import firebase
const functions = require('firebase-functions');

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

exports.sendNotification = functions.database.ref('/products/{product}')
.onUpdate((change, context) => {
        const prodName = context.data.child('name');
        const numProd = context.data.child('stock');
        if(numProd<=5){
        const payload = {
          notification: {
          title: 'Low stock!',
          body: `Product ${prodName} is running out.`
        }
      }

      const registrationToken = 'token'; 
     return admin.messaging().sendToDevice(registrationToken,payload)
    .then(function(response){
         console.log('Notification sent successfully:',response);
         return 1;
    })
    .catch(function(error){
         console.log('Notification sent failed:',error);
          });
        }    
});

【问题讨论】:

    标签: firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    显然您正在混淆两个 Firebase 的数据库服务:FirestoreRealtime Database

    事实上,您表明您的数据是按 collections 组织的(“集合的结构是这样的:products (collection) -> {productID} (document)”)表示您正在使用 Firestore(实时数据库没有集合)。

    但是您的后台触发器对应于实时数据库触发器,请参阅https://firebase.google.com/docs/functions/database-events

    如果您混合使用两种数据库服务的假设是正确的,您需要为 Firestore 使用后台触发器,请参阅 https://firebase.google.com/docs/functions/firestore-events,尤其是 onUpdate() 之一,如下所示:

    exports.updateUser = functions.firestore
        .document('/products/{productId}')
        .onUpdate((change, context) => {
          // Get an object representing the document
          const newValue = change.after.data();
    
          const prodName = newValue.name;
          const numProd = newValue.stock;
    
          // ...
        });
    

    请注意,您似乎没有正确处理numProd &gt; 5 时的情况。你可能会抛出一个错误或者只是做return null;

    观看 Firebase 视频系列中有关“JavaScript Promises”的 3 个视频也是一个好主意:https://firebase.google.com/docs/functions/video-series/

    【讨论】:

    • 显然我确实混淆了两者。下次我会小心的。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2022-01-17
    • 2023-01-31
    • 2019-10-06
    • 1970-01-01
    • 2023-03-20
    • 2020-12-12
    相关资源
    最近更新 更多