我最近写了一个云函数,当文档中有特定更新时,它会向特定用户发送通知,并且运行良好。但是,正如你在我的代码中看到的那样,在每个案例中,我添加了代码来触发通知,只要案例满足,但用户收到通知,即使所有切换案例都失败了。我对这个问题真的很困惑。
为了得到更好的解释:服务状态有五种类型的
- 类型-1
- 类型-2
- 类型-3
- 类型-4
- 类型-5
我希望只有在ServiceStatus中更新了类型-1、3、5时才向用户发送通知,否则应忽略函数触发器。为此,我写了一个switch案例,但它并没有像我预期的那样起作用,它会触发所有五种类型的通知,尽管有两种案例不能满足要求。
我的代码:
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;
}
});
如果只想在状态字段被主动更改时发送消息,则需要比较该字段在写入操作之前和写入之后的值。
为此,从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
}