深究 Relay Connection 规范:在非关系型数据库中的分页实现
抛开简单的数组分页,本教程将教你如何在 MongoDB、Redis 或 Elasticsearch 中实现基于游标的 Connection 分页,并处理连接总数、边缘节点异形数据。 · 难度:入门 · +10XP
深究 Relay Connection 规范:在非关系型数据库中的分页实现
很多开发者将 Connection 规范误解为简单的 offset 分页。本课程将深入实现基于游标的 forward/backward 分页,并且考虑当数据库不支持直接游标(如 MongoDB ObjectId)时如何构造伪游标。你还会学习如何高效计算 totalCount 而不牺牲性能,以及处理连接中边缘(edge)包含额外的元数据(如 membership role)的场景。
async function resolveConnection(parent, args, context) {
const { first, after, last, before } = args;
const cursor = after ? decodeCursor(after) : null;
const query = { _id: cursor ? { $gt: cursor } : {} };
const items = await db.collection.find(query).limit(first + 1).toArray();
const hasNextPage = items.length > first;
const edges = items.slice(0, first).map(item => ({
cursor: encodeCursor(item._id.toString()),
node: item
}));
return { edges, pageInfo: { hasNextPage, hasPreviousPage: false } };
}