A separate table with sockets is made only in order to solve the problem of opening/closing several tabs in the browser by the user.
The list of users with the status (online/offline) is based on another table (users table). At the same time, if you have data duplication when building such a list in the application, this only means that you are incorrectly creating a query to the database and are not using other workarounds in your server action to get around it.
How to build the server logic correctly so that the list of users with the status is without duplicates, if an additional table with several records on sockets is used?
It’s simple:
-
The simplest option is a properly composed query:
We associate the table with sockets with the user table (join left
). We take all the necessary fields from the user table, and only one from the socket table (for example, record id
). Next, we summarize all the values by field from the socket table. In this case, all duplicates will collapse and the request will return only one record to each user, while the sum of the ids of all records will be indicated in the field from the socket table. Thus, we will easily identify the on-line/offline user at the moment. If the field will contain any value = online. If the field is empty = offline. And no duplicates!
-
The second option is also not complicated, but less effective because it will additionally load the web server. In the server action, you use a repit, the data source for which is the user table, and inside the repit you are already checking for each individual user. The check is also very simple - if there is at least one entry in the socket table = online user, if there are no entries = offline user.
To summarize. The table with sockets does not prevent you from creating a list of users with the status. However, it helps to solve the problem if your application is not a SPA and the user can open/close several tabs in it.