javascript - 使用 firebase 云功能时是否应该通过快照获取引用?

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

我编写这个简单的 firebase 云函数只是为了熟悉该产品!

它所做的只是复制添加到“userWriteable/userProfiles/”的数据

在文档中,您总是会看到它们使用 onCreate 回调中返回的快照来获取要写入的新数据库引用。

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

    const admin = require('firebase-admin');
    admin.initializeApp();


    exports.copyProfileFunctionA = functions.database.ref('userWriteable/userProfiles/{userId}')
        .onCreate((snapshot, context) => {
            // Grab the current value of what was written to the Realtime Database.
            const original = snapshot.val();

            return snapshot.ref.root.child(`userWriteable/userProfileCopies/${context.params.userId}`).set(original);
        });

    exports.copyProfileFunctionB = functions.database.ref('userWriteable/userProfiles/{userId}')
        .onCreate((snapshot, context) => {
            // Grab the current value of what was written to the Realtime Database.
            const original = snapshot.val();
            return admin.database().ref(`userWriteable/userProfileCopies/${context.params.userId}`).set(original);
        });

这有什么原因吗?或者我可以像函数 copyProfileFunctionB 中那样做吗?

使用 functionA 相对于 functionB 是否有任何性能/成本优势?

两个函数都写入“userWriteable/userProfileCopies/”。

通过admin.database()获取引用是否更昂贵?

最佳答案

最好使用快照中的引用,因为它由已初始化且可能已连接的管理 SDK 实例提供支持。直接初始化和使用 Admin SDK 是可以的,但它可能会导致您的函数等待另一个连接(如果尚未连接),并且现在运行您的代码的每个服务器实例可能持有两个到数据库的连接。

关于javascript - 使用 firebase 云功能时是否应该通过快照获取引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886529/

相关文章:

javascript - 当作为函数参数提供时,有没有一种方法可以在不引用对象的情况下访问对象属性?

javascript - 粒子不是从 particles.js 生成的

php - 用 PHP 或 JavaScript 处理的大数组

ios - 集成 Firebase 数据库后的链接器错误

javascript - 传递异步获取的属性

javascript - 如何在 Cloud Functions for Firebase 中实现 json 对象?

python - Google Cloud Functions (Python) 中的随机连接错误

javascript - 我的按钮中的事件监听器无法正常工作,该功能在单击事件之外正常运行,但是当我单击按钮时它不起作用

android - 使用通过推送创建的节点更新 Firebase 数据库

javascript - Cloud Functions 错误 : Function returned undefined, 预期的 Promise 或值,以及 TypeError:无法读取未定义的属性 'First_Name'