javascript - 如何获得不同类型的通知?
问题描述
我不知道如何从我要发送的 index.js 中的 Firebase 云功能向设备发送不同类型的通知(评论通知)(如通知)。
我正在使用此代码向设备发送以下通知,但我不知道如何获得其他通知。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notification/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to : ', user_id);
const fromUser = admin.database().ref(`/notification/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
const from_message = fromUserResult.val().message;
console.log('You have new notification from : ', from_user_id);
const userQuery = admin.database().ref(`users/${from_user_id}/username`).once('value');
const deviceToken = admin.database().ref(`users/${user_id}/device_token`).once('value');
return Promise.all([userQuery,deviceToken]).then(result =>{
const userName = result[0].val();
const token_id = result[1].val();
const payload1 = {
notification:{
title: "some is following you",
body: `${userName} is following you`,
icon: "default",
click_action : "alpha.noname_TARGET_NOTFICATION"
},
data:{
from_user_id:from_user_id
}
};
return admin.messaging().sendToDevice(token_id, payload1).then(result=>{
console.log("notification sent");
});
})
.then(response => {
console.log('This was the notification Feature');
return true;
}).catch(error => {
console.log(error);
//response.status(500).send(error);
//any other error treatment
});
});
});
解决方案
您可以更改发送到 /notification/${user_id}/${notification_id} 节点的内容,以包含可让您在云函数中识别和创建不同通知的字段。
例如,您可以添加一个类型字段,然后:
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
const from_message = fromUserResult.val().message;
const from_type = fromUserResult.val().type;
然后您可以根据类型构建通知:
if(from_type === NOTIFICATION_FOLLOW){
payload1 = {
notification:{
title: "some is following you",
body: `${userName} is following you`,
icon: "default",
click_action : "alpha.noname_TARGET_NOTFICATION"
},
data:{
from_user_id:from_user_id
}
};
}else{
//set payload1 for a different notification
}
添加有效负载所需的任何字段并根据需要扩展控制结构。
推荐阅读
- google-sheets - 将查询结果改写为时间
- kubernetes - Minikube 的 CoreDNS 无法从 JVM 解析名称
- java - 从内部将 url 记录到 Spring 控制器
- javascript - React Native firebase OTP 仅适用于测试号码,不适用于我的真实号码
- amazon-web-services - 如何在 common.tfvars 中注入环境变量
- sql-server - SSIS 包通过凭据帐户失败
- javascript - 从 Firebase 实时数据库中删除数据并在 javascript 中更新应用程序
- mysql - 三表连接查询不显示任何数据
- node.js - Microsoft Teams:为 NodeJS 机器人提供将自适应卡片转换为图像的可能性
- microsoft-graph-api - 未找到段“siteCollections”的资源