javascript - OnCreate 函数未触发但 OnWrite 函数触发
问题描述
我有一个 oncreate 函数,当我在实时数据库中创建数据时,它似乎不会触发。我了解在实时数据库中创建新数据时会使用 onCreate。请参阅下面的代码。
我究竟做错了什么?
exports.getNewReport =
functions.database.ref('/Hotel_Complaints/Users/{usersId}/')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
var user_id = context.params.usersId;
console.log(user_id);
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = snapshot.val();
var device_token = admin.database().ref('/Hotel_Staff/'+user_id+'/device_token').once('value');
return device_token.then(result => {
var token_id = result.val();
console.log(token_id);
var str = eventSnapshot.issue_description;
var payload = {
notification: {
title: "New complaint",
body: "New complaint for your department",
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToDevice(token_id, payload).then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
return;
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
});
解决方案
通过稍微调整你的承诺链,它应该可以解决问题,见下文:
exports.getNewReport = functions.database.ref('/Hotel_Complaints/Users/{usersId}/')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
var user_id = context.params.usersId;
console.log(user_id);
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = snapshot.val();
var device_token = admin.database().ref('/Hotel_Staff/' + user_id + '/device_token').once('value');
return device_token
.then(result => {
var token_id = result.val();
console.log(token_id);
var str = eventSnapshot.issue_description;
var payload = {
notification: {
title: "New complaint",
body: "New complaint for your department"
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToDevice(token_id, payload);
})
.then(response => {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
return null;
})
.catch(error => {
console.log("Error sending message:", error);
return null
});
});
推荐阅读
- python - 如果事务由两行或更多行表示,是否有办法使用 python 对事务(日志)数据进行聚类?
- python - 如何获得分数以更新并显示在屏幕上?
- regex - pandas df中数字的条件替换
- reporting-services - SSRS - 如何计算由表达式生成的列中的值?
- node.js - Firestore 安全规则:如何通过安全规则强制在 Firestore 文档中创建的字段数?
- python - 使用 Azure 机器学习服务训练大型模型时如何克服 TrainingException?
- php - $str[n] 可以用于汉字字符串吗?
- java - How to read heap status with jdk 11?
- python - How to use RegEx in an if statement in Python?
- c# - how to set "table direction", using openxml.wordprocessing