You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Strapi自定义API响应格式化为带分页的内容类型端点格式?

实现Strapi自定义API的标准分页响应格式

当然可以,直接复用Strapi核心控制器的内置逻辑或格式化工具就能实现,无需额外插件,以下是几种可靠方案:

方案一:复用核心控制器的find方法(最快)

如果你的自定义API基于现有内容类型,直接调用对应内容类型核心控制器的find方法,它会自动处理分页参数解析、结果格式化和meta生成:

// src/api/your-custom-route/controllers/your-custom-route.js
module.exports = {
  async customList(ctx) {
    // 调用目标内容类型的核心find方法,自动处理分页和格式化
    const response = await strapi.controller('api::post.post').find(ctx);
    
    // 可在此对response.data做自定义修改(比如添加字段)
    response.data = response.data.map(item => ({
      ...item,
      attributes: {
        ...item.attributes,
        custom_tag: '自定义标识'
      }
    }));
    
    // 直接返回标准结构
    ctx.body = response;
  }
};

方案二:用createCoreController扩展核心逻辑

如果需要基于现有内容类型做自定义查询,用Strapi的控制器工厂创建扩展控制器,继承内置的分页和格式化能力:

// src/api/post/controllers/post.js
const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::post.post', ({ strapi }) => ({
  async find(ctx) {
    // 调用父类的find方法,自动生成带分页的标准响应
    const { data, meta } = await super.find(ctx);
    
    // 自定义数据处理示例
    const processedData = data.map(item => {
      // 过滤或修改attributes字段
      delete item.attributes.sensitive_field;
      return item;
    });
    
    // 返回标准结构
    ctx.body = {
      data: processedData,
      meta: meta
    };
  }
}));

方案三:完全自定义查询的手动实现

如果是完全独立的自定义查询(不基于现有内容类型),手动处理分页参数并生成标准格式:

// src/api/custom-endpoint/controllers/custom-endpoint.js
module.exports = {
  async customQuery(ctx) {
    // 解析Strapi标准分页参数
    const { page = 1, pageSize = 25 } = ctx.query;
    const limit = parseInt(pageSize);
    const offset = (parseInt(page) - 1) * limit;
    
    // 执行自定义查询(含总数统计)
    const [results, total] = await Promise.all([
      strapi.db.query('api::custom-model.custom-model').findMany({
        limit,
        offset,
        // 你的查询条件、关联查询等
        where: { status: 'published' },
        populate: ['category']
      }),
      strapi.db.query('api::custom-model.custom-model').count({
        where: { status: 'published' } // 和查询条件保持一致
      })
    ]);
    
    // 生成标准分页meta
    const pagination = {
      page: parseInt(page),
      pageSize: limit,
      pageCount: Math.ceil(total / limit),
      total: total
    };
    
    // 格式化数据为Strapi标准结构(id + attributes)
    const formattedData = results.map(item => {
      const { id, ...attributes } = item;
      return { id, attributes };
    });
    
    // 返回最终响应
    ctx.body = {
      data: formattedData,
      meta: { pagination }
    };
  }
};

常见问题排查

之前扩展核心控制器未成功,大概率是以下原因:

  • 未正确调用super.find(ctx)获取内置处理后的data和meta对象
  • 直接返回了原始数据数组,而非包含data和meta的顶层对象
  • 分页参数未按Strapi标准(page/pageSize)传递,导致内置逻辑未触发

内容的提问来源于stack exchange,提问作者Alian Diaz Perez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 00:02:49