View counter in strapi: With lifecycle hooks? But how to use them?

I have a similar functionality in place. I manage it as per below.

In my article model, I have a integer field with 0 as default named viewCount.

And I have custom controller in place as below.
api/article/config/routes.json

{
     "method": "PATCH",
      "path": "/articles/:slug/view",
      "handler": "article.logView"
}

api/article/controllers/article.js

async logView(ctx) {
    const { slug } = ctx.params;
    try {
      const article = await strapi.services.article.findOne({ slug });
      await strapi.services.article.update(
        { id: article.id },
        { views: parseInt(article.views) + 1 }
      );
      return ctx.send({
        success: true,
      });
    } catch (error) {
      console.error(error);
      return ctx.send({
        success: false,
      });
    }
}

And then in mounted method (Nuxt) make a request to this endpoint.

PS: You can also have logview count based on id or other unique param instead slug as well.

3 Likes