繁体   English   中英

如何在使用Cloud Functions触发的事件上推送通知

[英]How to push notification on Event trigerred with Cloud Functions

我无法创建在RealTimeDatabase中发生特定事件时推送通知的函数。 目前,我已经能够从Web上提取此函数,因为我几乎不了解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对象的日期与今天相同时推送通知,并且仅在用户激活通知设置时才执行此操作(这是配置文件中存储的布尔值)。

这是我的数据库的屏幕截图: 在此处输入图片说明

任何帮助将不胜感激!

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM