javascript - 使用火基云功能时,是否应该通过快照获取参考?
问题描述
我写这个简单的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()
更昂贵的方式获得参考?
解决方案
最好使用快照中的 ref,因为它由已经初始化并且可能已经连接的管理 SDK 实例提供支持。直接初始化和使用 Admin SDK 是可以的,但它可能会导致您的函数等待另一个连接(如果尚未连接),并且现在运行您的代码的每个服务器实例都可能持有与您的数据库的两个连接。
推荐阅读
- java - 如何将日志写入 postgresql 数据库
- python - driver.page_source 未定义
- docker - 无法在容器之间工作的 Windows Server 2019 入口网络上获取 Docker Swarm
- karate - 有没有办法将有效负载内的 json 数组值用作可选字段?空手道 DSL
- ios13 - 从 iOS 13.6.1 升级到 iOS 14 时应用行为发生变化
- django - 在不复制模型/字段定义的情况下重命名 ModelSerializer 字段的 DRY 方法?
- javascript - javascript对象上的for循环
- c# - 使用 ASP .Net core 3.1 Web 服务运行 docker 容器时出现运行时错误
- ios - 使用私有队列 NSManagedObjectContext,我是否需要访问私有队列上 NSManagedObjects 的属性?
- javascript - p5.js 说:由于当前范围内未定义“createVector”而出现错误