Firebase的云功能在执行完毕之前中断

时间:2017-04-04 21:00:39

标签: firebase firebase-realtime-database google-cloud-functions

功能正在观察proposals/{jobid}/{propid}。添加新提案并且child("isinvitation")为空时,该函数会成功将新节点写入proposals/sent,然后向作业jobs/${jobid}的提案子项添加增量。

删除提案时,该功能失败。 userRef.child(jobid).remove()也不会被触发,减少工作jobs/${jobid}的提案子项也不会发生。

exports.CountProposals = functions.database.ref("/proposals/{jobid}/{propid}").onWrite((event) => {
    const jobid = event.params.jobid;
    const userId = event.params.propid;
    const isinvitation = event.data.child("isinvitation").val();
    if (!isinvitation) {
        const userRef = admin.database().ref(`users/${userId}/proposals/sent`);
        if (event.data.exists() && !event.data.previous.exists()) {
            userRef.child(jobid).set({
                timestamp: admin.database.ServerValue.TIMESTAMP
            });
        } else if (!event.data.exists() && event.data.previous.exists()) {
            userRef.child(jobid).remove();
        }
    }
    const collectionRef = admin.database().ref(`/jobs/${jobid}`);
                return collectionRef.once('value').then(snapshot => {
                        if (snapshot.val() !== null) {
                            const countRef = collectionRef.child("proposals");
                            countRef.transaction(current => {
                                            if (event.data.exists() && !event.data.previous.exists()) {
                                                            return (current || 0) + 1;
                                            } else if (!event.data.exists() && event.data.previous.exists()) {
                                                            return (current || 0) - 1;
                                            }
                            });
                        }
                });
});
  

控制台日志不会显示任何错误。

2 个答案:

答案 0 :(得分:0)

“每次Firebase实时数据库写入时都会触发的事件处理程序。” - https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onWrite

我个人也希望这也会在删除操作上被触发,但是,它可能类似于AngularFire,其中write操作不被视为remove操作。

您可以查看此内容并了解如何使其适应您的情况:https://firebase.google.com/docs/reference/functions/functions.database.DeltaSnapshot#changed

编辑:在尝试了我自己的一些功能后,它们似乎会为我删除。我会更多地研究你的代码。

答案 1 :(得分:0)

您的功能是尝试在多个位置进行多次写入。这些写入中的每一个都将生成跟踪其完成的不同承诺。您应该返回单个承诺,该承诺在所有工作完成后解决。就目前而言,你只是从collectionRef.once('value').then()返回一个承诺,这个承诺本身并没有返回跟踪交易完成情况的另一个承诺。

基本上,您需要小心跟踪所有使用promises的写入,通常使用Promise.all()来等待所有未完成的工作。

相关问题