簡體   English   中英

Firebase雲功能Firestore觸發器onWrite在本地測試時表現異常

[英]Firebase cloud function Firestore trigger onWrite not behaving as expected when testing locally

我正在使用Firebase Functions Shell在Node中本地測試Firestore觸發的Firebase Cloud Function。

當使用onWrite觸發器並通過從函數外殼程序調用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
})

在使用before和after進行調用以模擬文檔更新updateMonth({before:{foo:'old'},after:{foo:'new'}})它可以按預期工作。 但是,僅用updateMonth({foo:'new'})調用時,文檔前后似乎都不存在:

i  functions: Preparing to emulate functions.
Warning: You're using Node.js v8.4.0 but Google Cloud Functions only supports v6.11.5.
+  functions: hi
+  functions: helloWorld
+  functions: updateMonth
firebase > updateMonth({before:{foo:'old'},after:{foo:'new'}})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: change.after.exists true
info: change.before.exists true
info: Old: { foo: 'old' }
info: Execution took 20 ms, user function completed successfully

firebase > updateMonth({foo:'new'})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: change.after.exists false
change.before.exists false
Old: undefined
Execution took 2 ms, user function completed successfully

我不確定如何獲得對正在創建的新文檔的引用。 我希望在這種情況下change.after.exists是正確的。

使用onWrite和onUpdate觸發器,在所有情況下都需要聲明文檔的“之前”和“之后”狀態。 您不能通過省略“ before”或“ after”鍵來簡化API。 例如,如果您只想測試文檔創建,請嘗試以下操作:

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

另外,如果您的代碼僅對文檔創建感興趣,那么僅在onCreate觸發器上編寫而不是嘗試在onWrite中確定文檔狀態可能會更容易。 就我個人而言,我避免使用onWrite並使用其他三個,因為它們更容易推斷出實際進行的更改。

經過多次迭代,事實證明該解決方案非常簡單。 為了成功地模擬一個新的文檔創建過程,該過程將在使用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的一個很好的增強。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM