I want to save views of articles/posts in strapi as a simple integer value.
Do you know an approach how to have something like a view counter in strapi? So every time an articles is viewed in the client an counter should increment. Do you know a solution for this?
I want to get the most viewed articles - so I think I need this value.
My thought was to use lifecycle hooks for this. But which one is the right (maybe afterFindOne, but I’m not sure)? And how can I update the the data in the afterFindOne-hook? I seen an example for the beforeCreated-hook, but in this hook I have the data of the model/entity.
And another question: When an afterFindOne-hook should be a solution, will this hook be called when I query data with graphql or just for the rest api call?
And use the query system in say a beforeFind or beforeFindOne to get the existing count +1. There is a risk of a race condition so maybe the controller method is better as you can do more complex logic (like checking for false positives via IP checking ect)
When I try it with fix values in the update part (for example with id 1 and views 15) it works, so it seems that the query.findOne is not working correctly. Or does this hook produces an infinite loop?
Unfortunately I don’t know how to see console.log output in postman for test/debug.
I just changed the {id: params.id } to {id: result.id } because I don’t know which data is in params but the result has an id.
Generally it’s really hard for me to debug the lifecycle-code. I insert some console.log but I don’t see them in browser or postman. Do you have any tip how to debug these hooks to see the console.log?
I’m still confused about how to add a view counter for each post on strapi. May I ask the source code for those of you who have the same problem to solve this problem. i stuck 2 days to solve this problem.
Hi! Were you able to see the logs in the server side? I don’t see anything in my console (server-side). I’ve also tried attaching a debugger but nothing is logged in debugger.
How did you manage the permissions? I find it difficult to enable the update of a field like this without enabling updating the entire article. How do you manage permissions for certain fields of an entity?
Because you’re already in the endpoint controller you can update the entity with no permission check. The normal /update endpoint still performs the check.