I am making a 1 vs 1 game matching system with the help of realtime database. When user sign in, it will generate a record in users table. When there are 2 player user status are placeholder then cloud function will generate a gameInfo for these 2 player and change their user status to waiting. What I am doing is make a trigger function to observe users/{uid} when it status child are placehold then call matchmaker function to generate gameInfo with unique gameId. But the problem is when trigger onWrite function run first time, theoretically there are only one user with placeholder status, however the database changed so quick in some case when iterate the database users table it has two player with placeholder status. So there are wired things happen sometimes, after two trigger function callbacks there should be only one gameId record in gameInfo because two player join in one game room with unique gameId, but it generate two unique gameId record sometimes. How can I avoid this wired thing happen.
Here is the database table.
And here is part of my cloud function code. For the matchmaker function, it will generate gameId record in games table if there are two players in the map waitingPlayers.
export const searchWaitingPlayers = functions.database.ref("users/{uid}").onWrite( (change, context) => {
if (!change.after.exists()) {
console.log("uid deleted");
return null;
} else {
if (change.after.child("status").val() !== "placeholder") {
console.log("user's status is not placeholder");
waitingPlayers.delete(change.after.key);
} else {
waitingPlayers.clear();
admin.database().ref("users").once("value").then(async (users) => {
users.forEach((user) => {
if (user.child("status").val() === "placeholder") {
waitingPlayers.set(user.key, user.child("username").val());
}
});
matchmaker();
});
}
return null;
}
});