【问题标题】:Update given field value with every fetch request in Strapi使用 Strapi 中的每个获取请求更新给定的字段值
【发布时间】:2020-03-24 01:45:30
【问题描述】:

我有一个简单的 Strapi 支持的 CMS,它具有 post 内容类型。此文档(内容类型)具有 titlesecondary titleexcerptbody 等字段。现在我希望能够记录此文档中每个条目的查看次数。

所以,我添加了一个名为 views 的数字字段,其默认值为 0。按照 Strapi 文档中的说明,我将以下代码添加到我的 api 模型中(/api/post/models/Post.js):

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

我知道beforeFetch 方法中的任何 sn-p 都应该在任何 fetch 操作之前触发和执行,这就是 post 查询在 GraphQL 中所做的。但是,尽管进行了多次提取,但该字段中的值保持不变。任何可以给出我哪里出错的想法的 Strapi 开发人员? 完整代码可以在https://github.com/amitschandillia/proost/blob/master/dev/api/post/models/Post.js找到。

P.S.:我尝试在 GraphQL Playground 中 https://dev.schandillia.com/graphql 执行的查询是:

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

【问题讨论】:

    标签: strapi


    【解决方案1】:

    为此我建议你理解这个概念https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#backend-customization

    然后您将不得不自定义 Post API 的 findOne 控制器功能。

    您将在此处找到要更新的默认功能。 https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#controllers

    它应该是这样的:

    路径—— ./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;
      },
    

    这里有一个简短的视频来帮助https://www.loom.com/share/df0cb65c52b0478d994c3732fac84020

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      相关资源
      最近更新 更多