0
votes

I have a simple Strapi-backed CMS with a post content type. This document (content type) has fields like title, secondary title, excerpt, body, etc. Now I want to be able to record view counts for each entry in this document.

So, I have added to it a number field called views with 0 as its default value. Following instructions in the Strapi documentation, I added the following code to my api model (at /api/post/models/Post.js):

beforeFetchAll: async (model) => {
  model.views += 1;
},

I understand any snippet inside of the beforeFetch method ought to trigger and execute before any fetch operation which is what the post query does in GraphQL. However, despite several fetches, the value in this field stays unchanged. Any Strapi dev who could give an idea where I'm going wrong? The full code can be found at https://github.com/amitschandillia/proost/blob/master/dev/api/post/models/Post.js.

P.S.: The query I'm attempting to execute in GraphQL Playground at https://dev.schandillia.com/graphql is:

{
  posts(limit: 1, where: {slug: "one-post"}) {
    id
    title
    views
  }
}
1

1 Answers

4
votes

To do that I suggest you understand this concept https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#backend-customization

Then you will have to customize the findOne controller function of the Post API.

Here you will find the default function to udpate. https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#controllers

Here what it will should look like:

Path — ./api/post/controller/Post.js

  async findOne(ctx) {
    const entity = await strapi.services.post.findOne(ctx.params);

    const sanitized = sanitizeEntity(entity, { model: strapi.models.post });

    const newView = sanitized.views + 1;
    strapi.query('post').update({ id: sanitized.id }, {
      views: newView
    });

    return sanitized;
  },

Here a short video to help https://www.loom.com/share/df0cb65c52b0478d994c3732fac84020