Repository navigation
feat: paginate listEntries with scroll - #3282
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughContentService now aggregates Content Platform results via scroll pagination and fills entries after accumulation. Both PLP and PDP sources attempt an early single-entry fetch ( ChangesContent Platform changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ContentService
participant ContentPlatformClient
participant fillEntriesWithData
Client->>ContentService: request content (PLP/PDP or multiple)
alt single-entry path
ContentService->>ContentPlatformClient: getSingleContent(identifier)
ContentPlatformClient-->>ContentService: single entry (match?)
ContentService-->>Client: return single matched content
else multi-entry path
ContentService->>ContentPlatformClient: listEntries(params)
ContentPlatformClient-->>ContentService: entries + scroll
loop accumulate pages (<= MAX_PAGES)
ContentService->>ContentPlatformClient: listEntries(with scroll)
ContentPlatformClient-->>ContentService: more entries + scroll?
end
ContentService->>fillEntriesWithData: accumulated entries
fillEntriesWithData-->>ContentService: enriched entries
ContentService-->>Client: return selected content
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/core/src/server/content/service.ts (1)
49-62: Heads-up on performance on large content types. ⚡
fillEntriesWithDatafans out onegetEntryDatarequest per entry viaPromise.all(lines 125–133). Previously capped at one page; now it's unbounded. On content types with many entries this can spike concurrency against the CP backend and block the SSR request thread for a while.Consider batching with a small concurrency limit (e.g.,
p-limit-style, or a simple chunked loop) to keep tail latency predictable. Purely a scalability suggestion — no behavior change required for this PR.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/server/content/service.ts` around lines 49 - 62, fillEntriesWithData currently fans out a Promise.all over getEntryData for every entry returned by listEntries (called here), which can create unbounded concurrency for large content types; modify fillEntriesWithData to process entries in controlled batches or use a concurrency limiter (e.g., p-limit or a simple chunked loop) when invoking getEntryData so only N requests run in parallel (choose a small default like 5–10), keeping the same return shape; update the logic in fillEntriesWithData (and any helper that calls getEntryData) to await batches/limited promises sequentially to prevent spiking CP backend and long SSR blocking.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/server/content/service.ts`:
- Around line 52-56: The do/while loop calling
this.clientCP.listEntries(serviceParams, scroll) can hang if the returned scroll
token doesn't advance; add a safety cap inside the method that uses scroll,
e.g., track iterations and/or total entries (maxIterations and maxEntries) and
break the loop when either cap is reached, and also detect a non-advancing token
by comparing the newly returned scroll to the previous one and breaking if
identical; when breaking due to a cap or non-advancing token, emit a warn log
(use the existing logger in this service) including the last scroll value,
iteration count, and accumulated allEntries length to aid debugging.
- Around line 52-56: The call to clientCP.listEntries is passing a second
positional argument (scroll) but the API only accepts a single params object;
update the loop so you merge the current scroll token into the serviceParams
passed to listEntries (e.g., set serviceParams.scroll = scroll or create a
shallow copy with {...serviceParams, scroll}) before calling
this.clientCP.listEntries(serviceParams), then keep pushing result.entries into
allEntries and update scroll from result.scroll; ensure you remove the
second-argument usage and only call listEntries with the single merged params
object.
---
Nitpick comments:
In `@packages/core/src/server/content/service.ts`:
- Around line 49-62: fillEntriesWithData currently fans out a Promise.all over
getEntryData for every entry returned by listEntries (called here), which can
create unbounded concurrency for large content types; modify fillEntriesWithData
to process entries in controlled batches or use a concurrency limiter (e.g.,
p-limit or a simple chunked loop) when invoking getEntryData so only N requests
run in parallel (choose a small default like 5–10), keeping the same return
shape; update the logic in fillEntriesWithData (and any helper that calls
getEntryData) to await batches/limited promises sequentially to prevent spiking
CP backend and long SSR blocking.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 7d76a408-7fb3-48e4-9cdb-1629cff2d4eb
📒 Files selected for processing (1)
packages/core/src/server/content/service.ts
6c7ef8e to
4d4ac3a
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/core/src/server/content/service.ts (1)
55-55:⚠️ Potential issue | 🔴 Critical | ⚡ Quick win
listEntriescall shape still looks invalid for@vtex/client-cp.Line 55 still passes
scrollas a second positional argument. This was already flagged and can fail TS build iflistEntriesaccepts a single params object.Suggested fix
- const result = await this.clientCP.listEntries(serviceParams, scroll) + const result = await this.clientCP.listEntries({ + ...serviceParams, + ...(scroll ? { scroll } : {}), + })#!/bin/bash # Verify listEntries signature and current call sites (read-only) rg -nP '\blistEntries\s*\(' packages/core/src/server/content/service.ts -C2 fd -HI 'index.d.ts' node_modules/@vtex/client-cp 2>/dev/null | head -20 rg -nP '\blistEntries\b' node_modules/@vtex/client-cp/**/*.d.ts 2>/dev/null -C3🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/server/content/service.ts` at line 55, The call to this.clientCP.listEntries incorrectly passes scroll as a second positional argument; update the call to match `@vtex/client-cp`'s signature by passing a single options object (merge scroll into serviceParams or into a new object) instead of a second argument so listEntries receives one params object; locate the call in service.ts referencing this.clientCP.listEntries and adjust to something like listEntries({...serviceParams, scroll}) and update any related typing if needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/server/content/service.ts`:
- Around line 66-70: The current call to fillEntriesWithData(allEntries,
serviceParams, options.isPreview) can cause an unbounded Promise.all fan-out;
modify fillEntriesWithData (or its internal helper that fetches individual entry
data) to limit concurrency when iterating allEntries—e.g., use a concurrency
limiter (p-limit) or process entries in fixed-size batches/chunks and await each
batch before proceeding—so look for the function fillEntriesWithData and its
internal loop that maps entries to fetch operations and replace the direct
Promise.all over allEntries with a bounded concurrency mechanism that accepts a
configurable limit.
---
Duplicate comments:
In `@packages/core/src/server/content/service.ts`:
- Line 55: The call to this.clientCP.listEntries incorrectly passes scroll as a
second positional argument; update the call to match `@vtex/client-cp`'s signature
by passing a single options object (merge scroll into serviceParams or into a
new object) instead of a second argument so listEntries receives one params
object; locate the call in service.ts referencing this.clientCP.listEntries and
adjust to something like listEntries({...serviceParams, scroll}) and update any
related typing if needed.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b9288735-9cf6-4d33-96a1-ef366d67ae91
📒 Files selected for processing (1)
packages/core/src/server/content/service.ts
| return this.fillEntriesWithData( | ||
| allEntries, | ||
| serviceParams, | ||
| options.isPreview | ||
| ) |
There was a problem hiding this comment.
Pagination now creates unbounded parallel entry fetches.
With accumulated allEntries, fillEntriesWithData can fan out into a large Promise.all burst, which risks CP throttling and request latency spikes. Add a concurrency limit for entry-data fetches.
Suggested direction
- const data = await Promise.all(
- entries.map(async (entry) => {
+ const data: (ContentEntry & PageContentType)[] = []
+ const chunkSize = 10
+ for (let i = 0; i < entries.length; i += chunkSize) {
+ const chunk = entries.slice(i, i + chunkSize)
+ const partial = await Promise.all(
+ chunk.map(async (entry) => {
const entryData = await this.getEntryData(
{ ...serviceParams, entryId: entry.id },
isPreview
)
return this.mergeEntryWithData(entry, entryData)
- })
- )
+ })
+ )
+ data.push(...partial)
+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/src/server/content/service.ts` around lines 66 - 70, The
current call to fillEntriesWithData(allEntries, serviceParams,
options.isPreview) can cause an unbounded Promise.all fan-out; modify
fillEntriesWithData (or its internal helper that fetches individual entry data)
to limit concurrency when iterating allEntries—e.g., use a concurrency limiter
(p-limit) or process entries in fixed-size batches/chunks and await each batch
before proceeding—so look for the function fillEntriesWithData and its internal
loop that maps entries to fetch operations and replace the direct Promise.all
over allEntries with a bounded concurrency mechanism that accepts a configurable
limit.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/package.json`:
- Line 78: Update the dependency entry for "`@vtex/client-cp`" in package.json to
a valid published version; replace the non-existent "0.6.0" value with the
latest available "0.5.1" so the dependency resolves correctly (modify the
"`@vtex/client-cp`" version string in the dependencies block).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d9f17f26-d39c-4615-acf5-c32b1585a514
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (1)
packages/core/package.json
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/server/content/service.ts (1)
108-110:⚠️ Potential issue | 🟠 Major | ⚡ Quick winFix nullable contract for
getSingleContent/getFromCP.
directMatchis treated as optional here, butgetSingleContentis typed as always returningT. SincegetFromCPcan swallow not-found and returnundefined, this is an unsound type contract.Suggested fix
- async getSingleContent<T extends ContentData>( + async getSingleContent<T extends ContentData>( params: ContentParams - ): Promise<T> { + ): Promise<T | undefined> { @@ - private async getFromCP<T extends ContentData>( + private async getFromCP<T extends ContentData>( options: ContentOptions - ): Promise<T> { + ): Promise<T | undefined> { @@ } catch (err: unknown) { if (isNotFoundError(err)) console.warn('Content not found', err) else throw err + return undefined } }As per coding guidelines, “TypeScript files: Ensure type safety and avoid type assertions when possible” and “TypeScript strict mode MUST be enabled globally”.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/server/content/service.ts` around lines 108 - 110, The code treats directMatch as possibly undefined even though getSingleContent<T> is currently typed to always return T; update the contract to reflect reality by making getSingleContent (and any wrappers like getFromCP) return T | undefined (or throw on not-found consistently) and then propagate that nullable type to callers (including the call site using directMatch) or change getFromCP to throw instead of returning undefined; adjust the function signatures for getSingleContent<T> and getFromCP and update all call sites to handle the optional return (or enforce non-null by throwing inside getSingleContent) so the TypeScript types match runtime behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@packages/core/src/server/content/service.ts`:
- Around line 108-110: The code treats directMatch as possibly undefined even
though getSingleContent<T> is currently typed to always return T; update the
contract to reflect reality by making getSingleContent (and any wrappers like
getFromCP) return T | undefined (or throw on not-found consistently) and then
propagate that nullable type to callers (including the call site using
directMatch) or change getFromCP to throw instead of returning undefined; adjust
the function signatures for getSingleContent<T> and getFromCP and update all
call sites to handle the optional return (or enforce non-null by throwing inside
getSingleContent) so the TypeScript types match runtime behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1e340985-e4a7-4d21-a6a7-73d672cbe902
📒 Files selected for processing (1)
packages/core/src/server/content/service.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/server/content/service.ts`:
- Around line 84-87: The functions getSingleContent and getFromCP currently have
signatures returning Promise<T> but can return undefined on 404s; update their
return types to Promise<T | undefined> and modify getFromCP's error handler to
explicitly return undefined on 404 paths so the implementation matches the type;
locate and change the function signatures for getSingleContent and getFromCP and
add an explicit "return undefined" in getFromCP's catch/404 branch (and adjust
any callers, e.g., the code using plpParams) to handle the widened return type.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 23fac8a8-436c-4f87-aab0-bf1e442b7061
📒 Files selected for processing (1)
packages/core/src/server/content/service.ts
| const directMatch = await this.getSingleContent<PLPContentType>(plpParams) | ||
| if (directMatch) { | ||
| return directMatch | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -e
echo "=== PLP fast-path ==="
sed -n '83,87p' packages/core/src/server/content/service.ts
echo
echo "=== getSingleContent signature ==="
sed -n '31,40p' packages/core/src/server/content/service.ts
echo
echo "=== getFromCP implementation ==="
sed -n '123,137p' packages/core/src/server/content/service.tsRepository: vtex/faststore
Length of output: 1027
Widen return types to make undefined returns explicit.
getSingleContent and getFromCP are typed as Promise<T> but implicitly return undefined when a 404 occurs. Change the return types to Promise<T | undefined> and add an explicit return undefined in the getFromCP error handler to match the implementation and maintain strict TypeScript compliance.
Suggested fix
async getSingleContent<T extends ContentData>(
params: ContentParams
- ): Promise<T> {
+ ): Promise<T | undefined> {
const options = this.createContentOptions(params)
if (isContentPlatformSource()) {
return this.getFromCP<T>(options)
}
return getPage(options.cmsOptions)
}
@@
private async getFromCP<T extends ContentData>(
options: ContentOptions
- ): Promise<T> {
+ ): Promise<T | undefined> {
const params = this.convertOptionsToParams(options)
try {
const entry: PageContentType = await this.getEntry(
params,
options.isPreview
)
return entry as T
} catch (err: unknown) {
- if (isNotFoundError(err)) console.warn('Content not found', err)
- else throw err
+ if (isNotFoundError(err)) {
+ console.warn('Content not found', err)
+ return undefined
+ }
+ throw err
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const directMatch = await this.getSingleContent<PLPContentType>(plpParams) | |
| if (directMatch) { | |
| return directMatch | |
| } | |
| async getSingleContent<T extends ContentData>( | |
| params: ContentParams | |
| ): Promise<T | undefined> { | |
| const options = this.createContentOptions(params) | |
| if (isContentPlatformSource()) { | |
| return this.getFromCP<T>(options) | |
| } | |
| return getPage(options.cmsOptions) | |
| } | |
| private async getFromCP<T extends ContentData>( | |
| options: ContentOptions | |
| ): Promise<T | undefined> { | |
| const params = this.convertOptionsToParams(options) | |
| try { | |
| const entry: PageContentType = await this.getEntry( | |
| params, | |
| options.isPreview | |
| ) | |
| return entry as T | |
| } catch (err: unknown) { | |
| if (isNotFoundError(err)) { | |
| console.warn('Content not found', err) | |
| return undefined | |
| } | |
| throw err | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/src/server/content/service.ts` around lines 84 - 87, The
functions getSingleContent and getFromCP currently have signatures returning
Promise<T> but can return undefined on 404s; update their return types to
Promise<T | undefined> and modify getFromCP's error handler to explicitly return
undefined on 404 paths so the implementation matches the type; locate and change
the function signatures for getSingleContent and getFromCP and add an explicit
"return undefined" in getFromCP's catch/404 branch (and adjust any callers,
e.g., the code using plpParams) to handle the widened return type.
There was a problem hiding this comment.
Safe for now: directMatch short-circuits before reaching here in most cases, keeping entry count small.
There was a problem hiding this comment.
@hellofanny — fair point on the runtime path. The directMatch fast-path does make hitting an unhandled undefined very unlikely in practice.
The TypeScript concern remains at compile time though: Promise<T> vs the actual Promise<T | undefined> is a silent lie to the type checker, and a future caller of getSingleContent could miss the undefined case without any compiler warning. Would you like to open a follow-up issue to track making the types honest (Promise<T | undefined>) so it doesn't get lost?
✏️ Learnings added
Learnt from: hellofanny
Repo: vtex/faststore PR: 3282
File: packages/core/src/server/content/service.ts:84-87
Timestamp: 2026-06-01T16:02:47.102Z
Learning: In `packages/core/src/server/content/service.ts` (vtex/faststore), `getSingleContent` and `getFromCP` are typed as `Promise<T>` but can implicitly return `undefined` on 404 (via `isNotFoundError`). The team accepted this for now because the `directMatch` early-return in `getPlpContent`/`getPdpContent` short-circuits before most undefined paths are reached at runtime. A future improvement would widen the return types to `Promise<T | undefined>` and add an explicit `return undefined` in `getFromCP`'s catch block for strict TypeScript compliance.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
3f15eec to
6b9cb57
Compare
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |

What's the purpose of this pull request?
ContentService.getPagewas returning only the first page of entries from Content Platform becauselistEntrieswasn't following thescrolltoken. Result: pages backed by CP silently missed content beyond the first batch.How it works?
In
packages/core/src/server/content/service.ts, the singlelistEntriescall is replaced by a loop that accumulates entries while ascrolltoken is returned, then passes the full list tofillEntriesWithData.How to test it?
Starters Deploy Preview
N/A
References
N/A
Summary by CodeRabbit
Bug Fixes
Enhancements
Notes