రెండు strategies: offset-based (limit/offset) మరియు cursor-based. GraphQL కు built-in pagination లేదు, కానీ community standard అనేది cursor pagination ను ఫార్మలైజ్ చేసే Relay Connection spec.
రెండు strategies: offset-based (limit/offset) మరియు cursor-based. GraphQL కు built-in pagination లేదు, కానీ community standard అనేది cursor pagination ను ఫార్మలైజ్ చేసే Relay Connection spec.
items(limit: 10, offset: 20)) సరళమైనది కానీ live data పై విఫలమవుతుంది: user page చేస్తున్నప్పుడు ఒక row insert అయితే, items మారిపోతాయి మరియు మీకు duplicates లేదా gaps కనిపిస్తాయి. deep offsets వద్ద ఇది నెమ్మదిగా కూడా అవుతుంది (DB ఇంకా skip చేసిన rows ను scan చేస్తుంది).ఒక connection list ను edges (ప్రతిదానికి ఒక cursor మరియు node) మరియు pageInfo లో చుడుతుంది:
type Query {
posts(first: Int!, after: String): PostConnection! # first = page size, after = cursor
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}
type PostEdge {
cursor: String! # opaque token for THIS node's position
node: Post! # the actual item
}
type PageInfo {
endCursor: String # feed this back as 'after' for the next page
hasNextPage: Boolean! # so the client knows when to stop
}
// resolver: fetch ONE extra row to compute hasNextPage cheaply
const rows = await db.posts.find({ after: args.after, limit: args.first + 1 });
const hasNextPage = rows.length > args.first;
const page = rows.slice(0, args.first);
return {
edges: page.map((p) => ({ node: p, cursor: encodeCursor(p.id) })),
pageInfo: { endCursor: page.at(-1) && encodeCursor(page.at(-1).id), hasNextPage },
};
cursor opaque — సాధారణంగా sort key యొక్క base64 — కాబట్టి clients దీన్ని number గా కాకుండా token గా పరిగణిస్తాయి.
offset vs cursor ను ఎంచుకోవడం మీరు concurrent writes కింద consistency మరియు deep-page performance ను అర్థం చేసుకున్నారని చూపుతుంది. Relay connection shape ను తెలుసుకోవడం ముఖ్యం ఎందుకంటే Apollo/Relay clients దాని కోసం built-in cache handling ను కలిగి ఉంటాయి.
జూనియర్ నుండి సీనియర్ వరకు వివరణాత్మక సమాధానాలతో IT ఇంటర్వ్యూ ప్రశ్నల లైబ్రరీ.
విరాళం