最近,我编写了一个云函数,当文档中有特定更新时,它会向特定用户发送通知,并且运行良好。但是,正如您在我的代码中所看到的,在每一种情况下,我都添加了代码以在情况满足时触发通知,但是用户收到通知,甚至所有的开关情况都失败了。我对这个问题真的很困惑。
更好的解释:ServiceStatus有五种类型
H 111Type-5H 212G 213
我希望只有在ServiceStatus中更新- 1、3、5类型时才向用户发送通知,否则函数触发器应该被忽略。为此,我编写了一个开关用例,但这不像我预期的那样工作,因为它会触发所有五种类型的通知,尽管两种情况不能满足。
我的代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.OrderUpdates = functions.firestore.document('orders/{ServiceID}').onWrite(async (event) =>{
const service_id = event.after.get('ServiceID');
const title = event.after.get('ServiceStatus');
let body;
const fcmToken = event.after.get('FCMToken');
const technician_name = event.after.get('TechnicianName');
switch(title){
case "Service Raised":
body = "Thanks for raising a service request with us. Please wait for sometime our customer care executive will respond to your request";
var message = {
token: fcmToken,
notification: {
title: title,
body: body,
},
"android": {
"notification": {
"channel_id": "order_updates"
}
},
data: {
"Service ID": service_id,
},
}
let response = await admin.messaging().send(message);
console.log(response);
break;
case "Technician Assigned":
body = "Our Technician " + technician_name + " has been assigned to your service request. You can contact him now to proceed further";
var message = {
token: fcmToken,
notification: {
title: title,
body: body,
},
"android": {
"notification": {
"channel_id": "order_updates"
}
},
data: {
"Service ID": service_id,
},
}
let response = await admin.messaging().send(message);
console.log(response);
break;
case "Service Completed":
body = "Your Service request has been successfully completed. Please rate and review our service and help us to serve better. \n Thanks for doing business with us..!!";
var message = {
token: fcmToken,
notification: {
title: title,
body: body,
},
"android": {
"notification": {
"channel_id": "order_updates"
}
},
data: {
"Service ID": service_id,
},
}
let response = await admin.messaging().send(message);
console.log(response);
break;
}
});发布于 2020-10-02 19:49:24
如果您只想在状态字段被主动更改时发送消息,则需要比较该字段在此写操作之前存在的值和在写入后存在的值。
为此,从before和after快照中获取字段值:
const beforeTitle = event.before ? event.before.get('ServiceStatus') : "";
const afterTitle = event.after ? event.after.get('ServiceStatus') : "";您将注意到,我还会检查event.before和event.after是否存在,因为您的云函数也将在文档创建(此时event.before未定义)和文档删除(此时event.after将未定义)时触发。
现在,使用这两个值,您可以检查ServiceStatus字段是否刚刚被赋予了一个值,该值应该触发一系列if语句发送的消息,如
if (afterStatus == "Service Raised" && beforeStatus != "Service Raised") {
... send relevant message
}https://stackoverflow.com/questions/64177031
复制相似问题