我编写这个简单的 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/