mcpField
A
api-pagination

api-pagination

github.com/secondsky开发242427 次安装5 周前更新
代码仓库

关于 api-pagination

面向开发者的 API 分页实现指南,介绍大数据集的分页策略,并涵盖响应格式与查询限制。

主要功能

  1. 01偏移、游标与键集策略
  2. 02分页响应结构示例
  3. 03页面大小上限建议
  4. 04索引与计数查询实践

适用场景

  1. 01为商品集合分页
  2. 02支持无限滚动信息流
  3. 03高效提供大型数据集

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/claude-skills --skill api-pagination

安装后在 Claude Code 中输入/api-pagination确认已加载。

详细介绍

API 分页

实现可扩展的分页策略,高效处理大型数据集。

分页策略

策略最适用场景性能
偏移量/限制小型数据集、简单 UIO(n)
游标无限滚动、实时场景O(1)
键集大型数据集O(1)

偏移量分页

app.get('/products', async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = Math.min(parseInt(req.query.limit) || 20, 100);
  const offset = (page - 1) * limit;

  const [products, total] = await Promise.all([
    Product.find().skip(offset).limit(limit),
    Product.countDocuments()
  ]);

  res.json({
    data: products,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit)
    }
  });
});

游标分页

app.get('/posts', async (req, res) => {
  const limit = 20;
  const cursor = req.query.cursor;

  const query = cursor
    ? { _id: { $gt: Buffer.from(cursor, 'base64').toString() } }
    : {};

  const posts = await Post.find(query).limit(limit + 1);
  const hasMore = posts.length > limit;
  if (hasMore) posts.pop();

  res.json({
    data: posts,
    nextCursor: hasMore ? Buffer.from(posts[posts.length - 1]._id).toString('base64') : null
  });
});

响应格式

{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 150,
    "totalPages": 8
  },
  "links": {
    "first": "/api/products?page=1",
    "prev": "/api/products?page=1",
    "next": "/api/products?page=3",
    "last": "/api/products?page=8"
  }
}

最佳实践

  • 设置合理的最大限制(例如,100)
  • 对大型数据集使用游标分页
  • 为排序字段建立索引
  • 尽可能避免 COUNT 查询
  • 切勿允许不受限制的页面大小

评论

支持 Markdown