Is there a way to request something from the backend and contiously search and refresh the database until it finds a match? then send the response

Issue

I am struggling to make my own matchmaking in a multiplayer game of two players. I have a button that says "play",and i want if the user presses it to change in database his schema property "inQueue to true" .

So after that i want to search the database to check who also is online and in queue(and meets requirement range for elo eg. player1:1200 ELO player2:1288 ) . But i dont want to send multiple requests until it finds a match.

iI was wondering if is there a way to send the request one time and when mongodb finds a match then return the response.
( i am using the mern stack with the help of sockets too)*

sample of database schema

Solution

The following middleware attempts to find a match on the database. If that is unsuccessful, another attempt is scheduled a second later. A JSON response is sent only after a successful attempt, but spaces are sent while waiting in the hope that this prevents a browser timeout.

.get("/path", function(req, res) {
  res.type("json");
  async function attempt() {
    var match = await User.find(...);
    if (match)
      res.end(JSON.stringify({match: match.username}));
    else {
      res.write(" ");
      setTimeout(attempt, 1000);
    }
  }
  attempt();
});

Answered By – Heiko Theißen

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.