Dev*_*ike 5 javascript firebase google-cloud-functions debounce
我有一个 Firebase 云函数,它根据 Firebase文档中提供的示例监控对我的实时数据库的更改。
我的函数工作正常,并按照编写的目的对每次更改执行。
话虽如此,并且根据 Firebase 的建议:
• 去抖动- 在Cloud Firestore 中侦听实时更改时,此解决方案可能会触发多个更改。如果这些更改触发的事件比您想要的多,请手动去抖动 Cloud Firestore 事件。
我只想这样做。
任何人都可以提供一个好的方法吗?
如果我们根据 Firebase 的示例查看此函数:
exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(
async (change, context) => {
// Get the data written to Realtime Database
const eventStatus = change.after.val();
// Create a reference to the corresponding Firestore document
const userStatusFirestoreRef = firestore.doc(`status/${context.params.uid}`);
// re-read the current data and compare the timestamps.
const statusSnapshot = await change.after.ref.once('value');
const status = statusSnapshot.val();
// If the current timestamp for this data is newer than
// the data that triggered this event, we exit this function.
if (status.last_changed > eventStatus.last_changed) {
return null;
}
// Otherwise, we convert the last_changed field to a Date
eventStatus.last_changed = new Date(eventStatus.last_changed);
// write it to Firestore
userStatusFirestoreRef.get().then((user: any) => {
user.forEach((result: any) => {
result.ref.set(eventStatus, { merge: true })
});
});
return;
});
Run Code Online (Sandbox Code Playgroud)
我应该如何尝试去抖动它的执行?
我可以尝试去抖动.onUpdate()事件吗?
我最初认为以下就足够了:
functions.database.ref('/status/{uid}').onUpdate(
debounce(async(change:any, context:any) => {
...
}, 10000, {
leading: true,
trailing: false
})
);
Run Code Online (Sandbox Code Playgroud)
但是,感谢@doug-stevenson 指出尝试以这种方式去抖动 onUpdate 事件是行不通的,原因如下:
“这是行不通的,因为函数的每次调用都可能发生在没有共享上下文的完全不同的服务器实例中。”
由于每个事件可能会传递多次,因此您必须跟踪context.eventId中提供的事件 ID 。如果您看到重复的事件,您就知道它正在重复。
有数十种策略可以做到这一点,而且不只有一种正确的方法。您可以将处理后的 ID 存储在数据库或其他持久存储中,但不能只将其存储在内存中,因为每个函数调用都可以在彼此完全隔离的情况下发生。
另请阅读“幂等性”,因为这是函数的属性,每次调用的行为方式都相同。
https://firebase.google.com/docs/functions/tips#write_idempot_functions
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |