Firebase云功能Firestore触发器onWrite在本地测试时表现异常

时间:2018-09-06 00:35:45

标签: node.js firebase google-cloud-firestore google-cloud-functions firebase-cli

我正在使用Firebase Functions Shell在Node中本地测试Firestore触发的Firebase Cloud Function。

在使用onWrite触发器并通过从函数外壳程序调用{​​{1}}传递新文档时,我无法获得对新文档的引用。

updateMonth({foo:'new'})

在模拟文档更新exports.updateMonth = functions.firestore .document('users/{userId}').onWrite((change, context) => { const document = change.after.exists ? change.after.data() : null; console.log("change.after.exists", change.after.exists) console.log("change.before.exists", change.before.exists) const oldDocument = change.before.data(); console.log("Old:",oldDocument) return true }) 之前和之后调用时,它可以按预期工作。 但是,仅用updateMonth({before:{foo:'old'},after:{foo:'new'}})调用时,文档前后似乎都不存在:

updateMonth({foo:'new'})

我不确定如何获得对正在创建的新文档的引用。在这种情况下,我希望change.after.exists是正确的。

2 个答案:

答案 0 :(得分:1)

使用onWrite和onUpdate触发器,在所有情况下都需要声明文档的“之前”和“之后”状态。您不能通过省略“ before”或“ after”键来简化API。例如,如果您只想测试文档创建,请尝试以下操作:

updateMonth({
    after:{foo:'new'}
})

此外,如果您的代码只对文档创建感兴趣,那么仅在onCreate触发器上编写而不是尝试在onWrite中确定文档状态可能会更容易。就我个人而言,我避免使用onWrite并使用其他三个,因为它们更容易推断出实际进行的更改。

答案 1 :(得分:1)

经过多次迭代,结果证明该解决方案非常简单。 若要成功模拟一个新文档的创建过程,该过程将在使用Firebase函数Shell本地模拟云功能时触发onWrite,则需要显式提供after属性,如updateMonth({after:{foo:'newVal'}})

firebase > updateMonth({after:{foo:'newVal'}})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
change.after.exists true
change.before.exists false
New: { foo: 'newVal' }
info: Execution took 291 ms, user function completed successfully

https://firebase.google.com/docs/functions/local-emulator#invoke_firestore_functions上的文档没有明确说明这一点,因此造成了混乱。也许这是添加到firebase-tools firebase functions:shell中的不错的增强功能。