【问题标题】:Strapi V4 how to modify data response for a component (dynamic zone)Strapi V4 如何修改组件的数据响应(动态区域)
【发布时间】:2022-08-11 17:26:51
【问题描述】:

想象一个编辑器使用动态区域向页面添加“最新产品”组件的情况:他们添加标题、摘要,然后将自动获取最新产品以在响应中可用。如何将此数据添加到组件的响应中?

我知道我们可以使用custom controller 覆盖内容类型的响应,但我找不到任何关于如何修改组件响应的信息。

也许还有一种我没有想到的替代方法,但是来自 Drupal 预处理——一切都是我能想到的背景。

任何帮助表示赞赏!

  • 我也想做同样的事情,你找到解决方案了吗?
  • @Kardon63 我刚刚在下面发布了我所做的事情。可能有更好的方法,但这是我目前能做的最好的!

标签: strapi


【解决方案1】:

我确信这不是最好的方法,但我为组件创建了一个服务,可以在内容类型控制器中使用它来修改响应。任何改进表示赞赏!

/api/custom-page/controllers/custom-page.js

'use strict';

/**
*  custom-page controller
*/

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::custom-page.custom-page', ({ strapi }) =>  ({

async find(ctx) {

const componentService = strapi.service('api::components.components');

let { data, meta } = await super.find(ctx);


data = await Promise.all(data.map(async (entry, index) => {

  if(entry.attributes.sections){
    await Promise.all(entry.attributes.sections.map(async (section, index) => {
      const component = await componentService.getComponent(section);
      entry.attributes.sections[index] = component;
    }));
  }
  return entry;

}));


return { data, meta };
},

}));

/components/services/components.js

'use strict';

/**
 * components service.
 */

module.exports = () => ({
  getComponent: async (input) => {

    // Latest products
    if(input.__component === 'sections.latest-products'){
      input.products = 'customdatahere';
    }

    return input;

  }
});

【讨论】:

    猜你喜欢
    • 2022-06-21
    • 2021-06-30
    • 2020-06-26
    • 2019-07-17
    • 1970-01-01
    • 2022-12-19
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多