来自Firebase

时间:2017-05-15 14:00:39

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

我是Javascript,Promises和Firebase的新手,所以这可能只是让我误解了一些基本的东西。我很感激任何指导!

我遇到的问题:我为某些事件保留了3个计数器。因此,每次将“项目”添加到“用户”时,我都会更新项目的全局计数,项目的项目数和用户数。

每当我使用它并对其进行测试时,这种方法都能很好地工作,但是有时出现问题,有时我会在几天后登录检查数据并且全局计数似乎翻了一番。例如,我将查看用户的计数,它将是200,但是如果我查看实际数据只有100个项目,让我认为计数事务递增2而不是1(或被调用两次) 。

我无法自己复制它,每当我使用此功能时,所有计数都会正确地增加一个。但如果我离开它几天,数字开始增加2或更多。

我的Firebase功能正在侦听数据库:

"use strict";

// Firebase requirements
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const utils = require('./utils');
admin.initializeApp(functions.config().firebase);

exports.updatePatientCount = functions.database.ref('/projects/{projectId}/users/{userId}/itemList/{itemId}').onWrite(event => {
    // Extract the projectKey and userId
    var projectId = event.params.projectId
    var userId = event.params.userId

    return utils.saveGlobals(admin, event, "itemCount", projectId, userId);
});

saveGlobals功能:

"use strict";

const counter = function (up, count) {
    if (up) {
        return (count || 0) + 1;
    }

    return (count || 0) - 1;
};

exports.saveGlobals = function (admin, event, ref, projectId, userId) {
    const gloRef = admin.database().ref("global-stats/global");
    const gloProjRef = admin.database().ref("global-stats/projects");

    var up = false;
    // If data was created increment by 1
    if (event.data.exists() && !event.data.previous.exists()) {
        up = true;
    } else if (!event.data.exists() && event.data.previous.exists()) {
        // If the data was deleted deincrement by 1
        up = false;
    } else {
        // If the data was updated return
        return;
    }

    // Update the global count
    const setGlo = gloRef.child(ref).transaction(current => {
        return counter(up, current);
    }).then(() => {
        console.log('Global updated.');
    });

    // Update the project count + set the project ID 
    const setPro = gloProjRef.child(projectId).child("projectId").set(projectId);
    const setGloPro = gloProjRef.child(projectId).child(ref).transaction(current => {
        return counter(up, current);
    }).then(() => {
        console.log('Global project updated.');
    });

    // Update the user count + set the ID
    const setUse = gloProjRef.child(projectId).child("users").child("ID-" + userId).child("userId").set(userId);
    const setGloUse = gloProjRef.child(projectId).child("users").child("ID-" + userId).child(ref).transaction(current => {
        return counter(up, current);
    }, ).then(() => {
        console.log('Global user updated.');
    });

    // Return the promises
    return setGlo && setPro && setGloPro && setUse && setGloUse;
}

我曾经把这个放在一起的例子:https://github.com/firebase/functions-samples/tree/master/child-count

我解压缩了saveGlobals()部分,因为它被多个递增不同计数器的云函数使用。

当项目添加到列表中时,任何人都可以看到任何原因导致事务应该开始递增多个计数吗?

0 个答案:

没有答案