Firebase Cloud功能会在onUpdate上触发两次

时间:2017-08-01 10:04:59

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

我为firebase collection - payments

设置了以下规则
"payments": {
    "$paymentId": {
        "totalAmount": {
        },
        "balanceAmount": {
            ".validate": "newData.val()<=data.child('totalAmount').val()"
        },
        "paymentDetails": {
            "$detailId": {
                "amount": {
                    ".validate": "newData.isString()"
                },
            }
        },
    }
}

以及为处理该集合的某些更新而编写的云函数:

exports.calculateBalance = functions.database
.ref('payments/{pushId}')
.onUpdate(event => {
    const paymentRef = event.data.adminRef;
    const payment = event.data.val();
    return paymentRef.once('value').then(snapshot => {
        var paidAmount = 0;
        snapshot.child("paymentDetails").forEach(function(child) {
            paidAmount += parseFloat(child.child("amount").val());
        });
        return paidAmount;
    }).then(snap => {
        payment.balanceAmount = parseFloat(payment.totalAmount) - snap;
        return paymentRef.set(payment);
    })
});

很简单,只要我添加付款详细信息,我想更新balanceAmount。这里的问题是,只要在该集合中发生更新,该函数就会触发两次。由于paymentRef.set(payment);行,第一次从应用程序和第二次显而易见。

有什么方法可以避免云功能的第二次触发?我无法在collection级别使用任何标记,因为付款详细信息的更新会多次发生。有人可以指导我正确的方向吗?

修改

注意 - 我输入了付款详细信息的编辑选项。

1 个答案:

答案 0 :(得分:4)

如果您只想在添加付款明细时更新余额,可以直接在付款明细上使用 onCreate 触发器。

尝试类似的东西(你必须更新你的案例的代码):

exports.calculateBalance = functions.database.ref('payments/{pushId}/paymentDetails/{detailId}').onCreate(event => {
    var paymentRef = event.data.adminRef.parent.parent;
    var paymentDetailSnapshot = event.data;
    var paymentDetailAmountSnapshot = paymentDetailSnapshot.child('amount');

    return paymentRef.child('balanceAmount').transaction(current => {
        return current - paymentDetailAmountSnapshot.val(); // Balance can be negative
    });
});

(使用该事务管理并发修改)

Transactions documentation.

注意

请直接使用数量 数量而不是字符串

<强>更新

添加此功能以管理更新:

exports.recalculateBalance = functions.database.ref('payments/{pushId}/paymentDetails/{detailId}').onUpdate(event => {
    var paymentRef = event.data.adminRef.parent.parent;

    var paymentDetailSnapshot = event.data;
    var previousPaymentDetailSnapshot = event.data.previous;

    var paymentDetailAmountSnapshot = paymentDetailSnapshot.child('amount');
    var previousPaymentDetailAmountSnapshot = previousPaymentDetailSnapshot.child('amount');

    return paymentRef.child('balanceAmount').transaction(current => {
        return current + previousPaymentDetailAmountSnapshot.val() - paymentDetailAmountSnapshot.val(); // Balance can be negative
    });
});