One solution is simply to count the moment the GET
the image is accessed.
GET /user/manga/113
To know the number of views, you can have an endpoint for this:
GET /user/manga/113/views
Each access will generate a record in a table, with some visitor data or simply a simple record of the visit. To know how many times it was visited, just count the records in the table. This solution, if you save information from the user you viewed, enables you to count views and count views excluding multiple visits from the same user (this is the concept of "unique visitors").
You could also create a "counter" column in the table and increment each view, as long as you make one UPDATE
in the direct counter in the database:
UPDATE manga SET views = views +1 WHERE id = ?
Letting the database itself handle the writing competition problem if multiple people are accessing the same image at the same time.
If you choose, for any reason, to make a SELECT
value, increment and then do the UPDATE
, you will have competition writing problems of this value. For example, if two calls from GET
occur at the same time in an image with 5 views, both will take the current value of the bank, increment in 1, and save. So instead of having 7 views you might have saved only 6 in the database.
It will depend a lot on the architecture of your solution. I would encapsulate it within a
Service
that offers access to the sleeves. Whenever the methodgetById
, service was accessed, it would increase the counter. I would not delegate it to the frontend, since you would be required to make 2 requests.– Leonardo Lima