javascript - 如何在使用 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 对象的日期与今天相同时推送通知,并且仅在用户激活通知设置时执行此操作。(这是存储在配置文件中的布尔值。)
任何形式的帮助将不胜感激!
解决方案
首先,您需要一个用户推送令牌或要发送到的主题。在您的情况下,我认为主题是正确的选择,因为您的用户可以通过简单的调用来订阅它,例如:
FirebaseMessaging.getInstance().subscribeToTopic("news")
然后,您可以通过从 adminAPI 返回一条消息来编写您的云函数,例如:
return admin.messaging().sendToTopic("news", payload, options);
您的实时数据库触发器看起来几乎正确。试一试吧:)
推荐阅读
- .htaccess - 除非我注释掉 htaccess 条目,否则无法上传文件
- oracle - 将不同行的值插入一行和多列,按列 x 的特定值分组
- javascript - Firestore 设置功能不做任何事情(React Native)
- python - 从python中的excel文件中删除波浪线和字符
- authentication - 如何使用烧瓶从推送器中获取 socket_id?
- python - 将 url 列表写入单元格,然后写入 pd.to_excel。URL 列表变成一个 url。如何避免这种情况?
- ios - iPad - 有没有办法有条件地保持本机键盘关闭?
- regex - 有没有办法使用正则表达式多次匹配花括号中的特定模式?
- javascript - 输入清除时输入值复位
- laravel - 如何使用 Laravel Query Builder 仅在一个连接表中进行区分?