微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Cloud Functions 数据操作问题中的 Firebase 管理员

如何解决Cloud Functions 数据操作问题中的 Firebase 管理员

Firebase 实时数据库结构

Database organizations

freepacks 包含两个重要元素:

  1. current,这是我将从移动应用下载的测验包 ID(从 quizpacks 检索)。
  2. history,这是一个节点,我在其中添加了随时间推移放入 current 中的所有测验包 ID,以及 Cloud Functions 中的预定函数

每次执行云功能时我需要做什么

第 1 步:current添加 history 的值和当前时间戳。

第 2 步:用另一个 不在历史上的测验包 ID 替换 current 值。

完成

我是如何努力实现这个目标的

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.scheduledFunction = functions.pubsub.schedule('* * * * *').onRun((context) => {

    // Current timestamp
    const dt = new Date();
    const timestamp = `${
        (dt.getMonth()+1).toString().padStart(2,'0')}/${
        dt.getDate().toString().padStart(2,'0')}/${
        dt.getFullYear().toString().padStart(4,'0')} ${
        dt.getHours().toString().padStart(2,'0')}:${
        dt.getMinutes().toString().padStart(2,'0')}:${
        dt.getSeconds().toString().padStart(2,'0')}`

    // Download the entire node 'freepacks'
    return admin.database().ref('quiz/freepacks').once('value').then((currentSnap) => {
        const currentPack = currentSnap.val().current;

        // Add current to history
        admin.database().ref('quiz/freepacks/history/' + currentPack).set(timestamp);
        
        // Download entire history node
        admin.database().ref('quiz/freepacks/history').once('value').then((historySnap) => {
            const history = historySnap.val();
            console.log('HISTORY: ' + history);

            // Download entire quizpacks node
            admin.database().ref('quiz/quizpacks').once('value').then((quizpacksSnap) => {
                for(quizpack in Object.keys(quizpacksSnap.val())) {
                    console.log('IteraNDO: ' + quizpack);
                    // Add the new current if it isn't in history
                    if (historySnap[quizpack] == undefined) {
                        admin.database().ref('quiz/freepacks/current').set(quizpack);
                        break;
                    }
                }
            });

        })

    });
    
});

我从之前的代码中得到了什么

起点:

Starting point

第一次执行:历史更新良好但更新current无效

First execution

第二次执行广告等等... current 不再更新(停留在 0)

我使用 JavaScript 和 Firebase Admin 的经验是 ~0...我的代码有什么问题?在此先感谢您的帮助!

解决方法

首先是所有读/写操作都返回承诺,因此您应该处理它们。在这个答案中,我使用了 async-await 语法。 .ref("quiz/freepacks") 获取完整节点,即当前节点和历史节点,因此您不必像在原始代码中那样再次查询历史节点。其他更改只是 Javascript 调整,例如使用 .find() 而不是 for-loop 等等..

尝试将您的函数更改为:

exports.scheduledFunction = functions.pubsub
  .schedule("* * * * *")
  .onRun(async (context) => {
    // Getting Date
    const dt = new Date();
    const timestamp = `${(dt.getMonth() + 1).toString().padStart(2,"0")}/${dt
      .getDate()
      .toString()
      .padStart(2,"0")}/${dt.getFullYear().toString().padStart(4,"0")} ${dt
      .getHours()
      .toString()
      .padStart(2,"0")}:${dt.getMinutes().toString().padStart(2,"0")}:${dt
      .getSeconds()
      .toString()
      .padStart(2,"0")}`;

    // Download the entire node 'freepacks'
    const currentSnap = await firebase
      .database()
      .ref("quiz/freepacks")
      .once("value");

    // Checking current free pack ID and array of previous free packs
    const currentPack = currentSnap.val().current || "default";
    const freeHistoryIDs = [
      ...Object.keys(currentSnap.val().history || {}),currentPack,];

    // Add current free pack to free history
    await firebase
      .database()
      .ref("quiz/freepacks/history/" + currentPack)
      .set(timestamp);

    // Download entire quizpacks node
    const quizpacksSnap = await firebase
      .database()
      .ref("quiz/quizpacks")
      .once("value");

    const quizPackIDs = Object.keys(quizpacksSnap.val() || {});

    const newPack = quizPackIDs.find((id) => !freeHistoryIDs.includes(id));
    console.log(newPack);
    if (!newPack) {
      console.log("No new pack found")
    }
    return firebase.database().ref("quiz/freepacks/current").set(newPack || "none");
  });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?