首页 > 解决方案 > 如何在使用 Cloud Functions 触发的事件上推送通知

问题描述

当我的 RealTimeDatabase 中发生某个事件时,我无法创建一个推送通知的函数。目前我已经能够从网上提取这个函数,因为我对 JavaScript 几乎一无所知,我不知道它到底在做什么..

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

var admin = require('firebase-admin');

admin.initializeApp();


exports.sendNotification = functions.database.ref('/tareas/{userId}/{tareasId}').onWrite((change, context) => {

  // Grab the current value of what was written to the Realtime Database.
  var descripcion = change.after.ref.parent.child('descripcion'); 
   var lista = change.after.ref.parent.child('lista');
   const snapshot = change.after.val;

  // Get the current userId
  var userId = change.params.userId

  // Notification details.
  const payload = {
    notification: {
      title: 'Nuevo Plan',
      body: `${descripcion} tienes un plan que completar "${lista}".`,
      sound: 'default',
      //clickAction: 'fcm.ACTION.HELLO',
      // badge: '1'
    },
    data: {
      extra: 'extra_data',
    },
  };



// Set the message as high priority and have it expire after 24 hours.
  const options = {
    collapseKey: 'demo',
    contentAvailable: true,
    priority: 'high',
    timeToLive: 60 * 60 * 24,
  };

有人可以指出我正确的方向,要添加什么?我已经尝试实现这个几个小时了!

我希望该功能在我的 Tareas 对象的日期与今天相同时推送通知,并且仅在用户激活通知设置时执行此操作。(这是存储在配置文件中的布尔值。)

这是我的数据库的屏幕截图: 在此处输入图像描述

任何形式的帮助将不胜感激!

标签: javascriptandroidgoogle-cloud-functions

解决方案


首先,您需要一个用户推送令牌或要发送到的主题。在您的情况下,我认为主题是正确的选择,因为您的用户可以通过简单的调用来订阅它,例如:

FirebaseMessaging.getInstance().subscribeToTopic("news")

然后,您可以通过从 adminAPI 返回一条消息来编写您的云函数,例如:

return admin.messaging().sendToTopic("news", payload, options);

您的实时数据库触发器看起来几乎正确。试一试吧:)


推荐阅读