javascript OnCreate函数未激发,但OnWrite函数激发

6bc51xsx  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(133)

我有一个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.

f0brbegy

f0brbegy1#

通过稍微调整你的promises链,它应该可以做到这一点,见下文:

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

    });

相关问题