I have been thinking about this title for a long time.
If we want to randomly pair two users and don't consider any conditions, What should I do in database structure and code?
Also, if we have many conditions to query the user, is it not suitable for using the Realtime database and I should use MySQL or something else?
I don't have the experiment in this field and like to know how most people would do.
Thank you.
CodePudding user response:
You should have a "pairs" node, which lists the pair of each user.
When a user wants to find a pair:
- Add a key-value node to "pairs", where the key is the UID, and the value is an empty string.
- Add a listener to your new node.
- Search in "pairs" for another user that has an empty string as a value.
- If found, change the values of both nodes to the other user's UID.
- When the listener callback will be called, it means some other user just paired with you, so you can use the value to know the UID of the other user. Also, don't forget to cancel the listener.
The reads and writes to the database should be atomic, in order to prevent bugs in the pairing process (like overriding an existing pair). Therefore, you should use firebase transactions.
If there are certain conditions for a pair, you can save the conditions' data in the node of the user, inside the "pairs" node (for temporary data), or inside the "users" node that you probably have already (for long term data).
Important
However!, this method leaks data about the existing pairs, and about the users that are waiting for a pair. I recommend moving the code to your server or to a cloud function. Security is really critical here! You should also write some strict security rules for the database.
Hope I managed to help!