[英]Correct way to check who is the first to set a property in firebase firestore
I'm creating a game using firebase firestore, and I need to tell which user started the game.我正在使用 firebase firestore 创建游戏,我需要告诉哪个用户启动了游戏。 The idea that I had was to have a
startedByPlayer: string
property and use a transaction to update this property.我的想法是拥有一个
startedByPlayer: string
属性并使用事务来更新此属性。 If this property is already set, then eventually return false;如果这个属性已经设置,那么最终返回false; otherwise, set this property with the current user and eventually return true.
否则,使用当前用户设置此属性并最终返回 true。
Since it's tough to test race conditions, I just wanted to make sure this was the right approach:由于很难测试比赛条件,我只是想确保这是正确的方法:
function tryToStartGame(player : Player) {
const ref = gamesRef.doc("game");
return db.runTransaction(function (transaction) {
return transaction.get(ref).then(function (game) {
if (!game.exists) {
return false;
}
const { startedByPlayer: startedByUser } = game.data() as Game;
if (!startedByUser) {
transaction.update(ref, { startedByUser: player.id });
return true;
}
return false;
});
});
}
Yes, this is a great idea, indeed.是的,这确实是个好主意。 Checking this way, it will cover already started games, so values are not replaced and no unnecessary writes are made or set the value properly, in case needed.
以这种方式检查,它将覆盖已经开始的游戏,因此不会替换值,也不会进行不必要的写入或正确设置值,以备不时之需。 And besides that, you have a function that will confirm via boolean, the creation, if either happened in that moment or if it was already done.
除此之外,您还有一个 function 将通过 boolean 确认创建,如果当时发生或已经完成。 So, I think you are covering needed points, in a not so complex model for you to program.
所以,我认为你在一个不那么复杂的 model 中涵盖了需要的点,供你编程。
I hope this information helps clarifies your doubts!我希望这些信息有助于澄清你的疑惑!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.