【发布时间】:2020-02-26 20:57:29
【问题描述】:
我有一个 Firebase 云函数,它根据 Firebase 的 documentation 中提供的示例监控我的实时数据库的更改。
我的函数工作正常,每次更改都按原样执行。
话虽如此,并且根据 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;
});
我应该如何尝试去抖动它的执行?
我可以尝试去抖动.onUpdate() 事件吗?
我最初认为以下就足够了:
functions.database.ref('/status/{uid}').onUpdate(
debounce(async(change:any, context:any) => {
...
}, 10000, {
leading: true,
trailing: false
})
);
但是,感谢@doug-stevenson 指出尝试以这种方式对 onUpdate 事件进行去抖动将不起作用,原因如下:
“这是行不通的,因为函数的每次调用都可能发生在完全不同的服务器实例中,没有共享上下文。”
【问题讨论】:
标签: javascript firebase google-cloud-functions debounce