首页 > 解决方案 > 使用火基云功能时,是否应该通过快照获取参考?

问题描述

我写这个简单的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()更昂贵的方式获得参考?

标签: javascriptfirebase-realtime-databasegoogle-cloud-functions

解决方案


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


推荐阅读