From 6a2aff3ecc94b6197103da73d06b2fc18900d86d Mon Sep 17 00:00:00 2001 From: Ben Newman Date: Thu, 30 Jan 2020 15:06:50 -0500 Subject: [PATCH] Address feedback on pagination examples raised in #5881. Follow-up to #5677. Thanks to @tafelito for actually trying out the code examples in the new cache policies documentation! --- docs/source/caching/cache-field-behavior.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/source/caching/cache-field-behavior.md b/docs/source/caching/cache-field-behavior.md index 7d8672dd78b..654a3b50545 100644 --- a/docs/source/caching/cache-field-behavior.md +++ b/docs/source/caching/cache-field-behavior.md @@ -336,7 +336,8 @@ const cache = new InMemoryCache({ merge(existing: any[], incoming: any[], { args }) { const merged = existing ? existing.slice(0) : []; // Insert the incoming elements in the right places, according to args. - for (let i = args.offset; i < args.offset + args.limit; ++i) { + const end = args.offset + Math.min(args.limit, incoming.length); + for (let i = args.offset; i < end; ++i) { merged[i] = incoming[i - args.offset]; } return merged; @@ -346,10 +347,16 @@ const cache = new InMemoryCache({ // If we read the field before any data has been written to the // cache, this function will return undefined, which correctly // indicates that the field is missing. - return existing && existing.slice( + const page = existing && existing.slice( args.offset, args.offset + args.limit, ); + // If we ask for a page outside the bounds of the existing array, + // page.length will be 0, and we should return undefined instead of + // the empty array. + if (page && page.length > 0) { + return page; + } }, }, }, @@ -394,10 +401,13 @@ const cache = new InMemoryCache({ const afterIndex = existing.findIndex( task => args.afterId === readField("id", task)); if (afterIndex >= 0) { - return existing.slice( + const page = existing.slice( afterIndex + 1, afterIndex + 1 + args.limit, ); + if (page && page.length > 0) { + return page; + } } } },