gpt4 book ai didi

javascript - OnCreate 函数未触发,但 OnWrite 函数触发

转载 作者:行者123 更新时间:2023-12-02 23:06:29 24 4
gpt4 key购买 nike

我有一个 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);
});

});
});

See log here.

最佳答案

通过稍微调整你的 promise 链,它应该可以达到目的,见下文:

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
});

});

关于javascript - OnCreate 函数未触发,但 OnWrite 函数触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57570286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com