API 分页、筛选与排序
通过分页返回大型数据集、允许客户端筛选和排序结果,并提供一致的查询参数,让您的 SaaS API 能够扩展。
API 分页、筛选与排序 是 CoddyKit 上的免费 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Powered SaaS: Stripe + Auth + Billing + Deploy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Not Return Everything?
An endpoint that returns 50,000 rows is slow, heavy, and crashes clients. Pagination returns data in manageable chunks, while filtering and sorting let clients ask for exactly what they need.
Offset Pagination
The simplest approach uses page and limit. You skip (page - 1) * limit rows and take limit rows.
GET /api/users?page=2&limit=20Implementing Offset in Prisma
Prisma exposes skip and take for offset pagination.
const users = await prisma.user.findMany({
skip: (page - 1) * limit,
take: limit
});Returning Metadata
Clients need to know how many pages exist. Return the data plus a total count and computed page info.
const total = await prisma.user.count();
return Response.json({
data: users,
page,
totalPages: Math.ceil(total / limit)
});The Offset Problem
Large offsets are slow because the database still scans skipped rows, and inserts can shift items between pages. For big or live datasets, prefer cursor pagination.
Cursor Pagination
A cursor points to the last item seen. The next request fetches rows after that cursor — fast and stable even as data changes.
const users = await prisma.user.findMany({
take: limit,
skip: 1,
cursor: { id: lastId },
orderBy: { id: 'asc' }
});Filtering by Query Params
Read filter params from the URL and build a where clause. Use contains for search-style filters.
const q = searchParams.get('search');
const where = q ? { name: { contains: q, mode: 'insensitive' } } : {};Combining Multiple Filters
Build the where object conditionally so only provided params apply. Prisma combines them with AND by default.
const where = {};
if (status) where.status = status;
if (minPrice) where.price = { gte: Number(minPrice) };Sorting Safely
Accept a sort field and direction, but whitelist allowed fields so clients cannot order by arbitrary or sensitive columns.
const allowed = ['name', 'createdAt', 'price'];
const field = allowed.includes(sort) ? sort : 'createdAt';
const orderBy = { [field]: dir === 'desc' ? 'desc' : 'asc' };Validating Query Params
Coerce and clamp inputs: cap limit so a client cannot request a million rows, and default page to 1.
const limit = Math.min(Number(searchParams.get('limit')) || 20, 100);
const page = Math.max(Number(searchParams.get('page')) || 1, 1);Best Practices
Design scalable list endpoints:
- Always paginate large collections
- Use cursor pagination for big or live data
- Return metadata (total, pages)
- Whitelist sort fields and clamp limits
Quick Check
Test your pagination knowledge.
Recap
You learned to build scalable list APIs:
- Paginate with
skip/takeor cursors - Return total and page metadata
- Build dynamic
whereclauses for filtering - Whitelist sort fields and clamp the limit
Your API now handles large datasets efficiently.
用 AI 导师学习 AI Powered SaaS: Stripe + Auth + Billing + Deploy — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「API 分页、筛选与排序」课时是免费的吗?
是的 — 「API 分页、筛选与排序」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程的其余内容,请升级到 CoddyKit PRO。 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程共包含 4 节课。
「API 分页、筛选与排序」这节课中我会学到什么?
通过分页返回大型数据集、允许客户端筛选和排序结果,并提供一致的查询参数,让您的 SaaS API 能够扩展。 你通过在浏览器中直接运行的动手代码来练习 AI Powered SaaS: Stripe + Auth + Billing + Deploy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Powered SaaS: Stripe + Auth + Billing + Deploy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「API 分页、筛选与排序」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课中编写并运行代码吗?
能。每节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- RESTful API 设计原则
- 数据库模式与 ORM
- 首批 API 端点
- API 分页、筛选与排序