云功能推送通知问题
Posted
技术标签:
【中文标题】云功能推送通知问题【英文标题】:Problem with cloud function push notification 【发布时间】:2021-01-02 20:22:49 【问题描述】:在我的 Flutter Firebase 应用程序中,我正在尝试配置推送通知,但我发现它非常具有挑战性,因为我对 javascript 非常陌生。下面的代码,我正在尝试根据用户活动项字段(评论)发送通知。如果活动项的评论字段为空,则表示该活动项的帖子正在被点赞,如果不为空,则表示该活动项的帖子正在被评论。大多数代码的工作原理是获取用户设备令牌、保存它,甚至是数据的控制台登录快照并将消息发送到设备。但问题是当云功能触发并将消息发送到用户设备时,消息正文似乎为空,我得到提示我没有在活动项的正确值上编写 switch 语句(评论)。几个月来我一直在审查这个,谢谢
//This part of the cloud function code to listens to new document on
// the activity path
exports.onCreateActivityNotification = functions.firestore
.document('/activities/userId/userActivities/userActivitiesId')
.onCreate(async (snapshot, context) =>
console.log('activity notification created', snapshot.data());
//getting user connected to the activity
const userId = context.params.userId;
const createdActivityItem = snapshot.data();
const usersRef = admin.firestore().doc(`users/$userId`);
const doc = await usersRef.get();
const androidNotificationToken =
doc.data().androidNotificationToken;
//checks if user has an androidnotification token
if(androidNotificationToken)
//sennds notification if users has a token
sendNotification(androidNotificationToken, createdActivityItem )
else
console.log('no notification token');
//function for sending the notification, I am very sure my problem is coming from this
//part of the code. I am not writing the switch statement on the right value. I think I
//need to get the exact fields of the activity item
function sendNotification(androidNotificationToken, userActivities)
let body;
switch (userActivities)
case userActivities.comment !== null:
body = `$userActivities.fromUserId commented :
$userActivities.comment`
break;
case userActivities.comment === null:
body = `$userActivities.fromUserId liked your punch`
break;
default:
break;
//creates message for push notification
const message =
notification: body: body,
token: androidNotificationToken,
data: recipient: userId,
;
//sends message with admin.messaging()
admin
.messaging()
.send(message)
.then(response =>
return console.log('message sent', response);
).catch(error =>
console.log('error sending message', error);
)
);
// This is the code to create the activity item for which triggers the cloud function
// just for reference
static void addActivityItem(
String currentUserId, Post post, String comment)
if (currentUserId != post.authorId)
activitiesRef.document(post.authorId).collection('userActivities').add(
'fromUserId': currentUserId,
'postId': post.id,
'seen': '',
'postImageUrl': post.imageUrl,
'comment': comment,
'timestamp': Timestamp.fromDate(DateTime.now()),
);
【问题讨论】:
【参考方案1】:尝试像这样更改您的开关:
switch (userActivities.comment)
case null:
body = `$userActivities.fromUserId commented : $userActivities.comment`
break;
default: body = `$userActivities.fromUserId liked your punch`
或考虑使用if else
【讨论】:
非常感谢。它工作得很好。当我更改 switch 语句时以上是关于云功能推送通知问题的主要内容,如果未能解决你的问题,请参考以下文章