【发布时间】:2021-06-26 17:04:38
【问题描述】:
我使用 Firestore 开发了一款游戏,但我注意到我的预定云功能中存在一些问题,该功能会删除 5 分钟前创建但未满或 已完成的房间
强>。为此,我正在运行以下代码。
async function deleteExpiredRooms() {
// Delete all rooms that are expired and not full
deleteExpiredSingleRooms();
// Also, delete all rooms that are finished
deleteFinishedRooms();
}
删除已完成的房间似乎可以正常工作:
async function deleteFinishedRooms() {
const query = firestore
.collection("gameRooms")
.where("finished", "==", true);
const querySnapshot = await query.get();
console.log(`Deleting ${querySnapshot.size} expired rooms`);
// Delete the matched documents
querySnapshot.forEach((doc) => {
doc.ref.delete();
});
}
但我在删除 5 分钟前创建的未满房间时遇到了并发问题(当房间中有 2 个用户时,一个房间已满,因此游戏可以开始)。
async function deleteExpiredSingleRooms() {
const currentDate = new Date();
// Calculate the target date
const targetDate = // ... 5 minutes ago
const query = firestore
.collection("gameRooms")
.where("full", "==", false)
.where("createdAt", "<=", targetDate);
const querySnapshot = await query.get();
console.log(`Deleting ${querySnapshot.size} expired rooms`);
// Delete the matched documents
querySnapshot.forEach((doc) => {
doc.ref.delete();
});
}
因为在删除房间的过程中,用户可以在房间被完全删除之前进入。
有什么想法吗?
注意:为了搜索房间,我使用的是交易
firestore.runTransaction(async (transaction) => {
...
const query = firestore
.collection("gameRooms")
.where("full", "==", false);
return transaction.get(query.limit(1));
});
【问题讨论】:
标签: javascript node.js firebase google-cloud-firestore concurrency