【发布时间】:2018-05-09 23:47:04
【问题描述】:
我想编写一个由 Firestore 写入事件触发的 Firebase 云函数。在函数内部,我必须知道 write 是否实际上是一个创建、更新或删除函数。逻辑略有不同,但我不想复制和粘贴三个不同的事件处理程序。如何判断它是哪种事件类型?
云文档让我很困惑。
Event 的文档说,在 FireStore 的情况下,事件实际上是一个 DeltaDocumentSnapshot。
https://firebase.google.com/docs/reference/functions/functions.Event
DeltaDocumentSnapshot 的文档表明该类没有关于事件本身的信息(例如,创建、更新或删除的指示),而只有目标文档:
https://firebase.google.com/docs/reference/functions/functions.firestore.DeltaDocumentSnapshot
我找到了示例,作者似乎通过检查当前或以前的文档是否存在来推断创建/更新/删除。我试过了,但我得到了一个错误。
https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js#L30
这是我尝试过的:
exports.updateLikeCount = functions.firestore
.document('likes/{likeId}').onWrite((event) => {
if (event.data.data().exists()) {
// Looks like the document still exists. It must be an update or create.
}
if (event.data.previous.data().exists()) {
// Looks like the document existed before. It must be an update or delete.
}
该代码因以下错误而失败:
TypeError: event.data.exists is not a function
【问题讨论】:
-
您从
child-count链接的代码使用event.data.exists()。您在其中添加了一个额外的data(),这不起作用。
标签: google-cloud-functions google-cloud-firestore