Skip to content

Refactor internal PaginatedResult API to have non-optional methods #2021

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 1, 2025

Conversation

VeskeR
Copy link
Contributor

@VeskeR VeskeR commented May 1, 2025

This changes condition-based function properties in the internal PaginatedResult to regular class methods.

The spec #TG5 does not specify if the link to the first page (or current) can be missing in the response and what should be done in such
case, so the new implementation is the best-effort attempt to bring the internal PaginatedResult API in line with the public API, while keeping the same function behavior as before.

The new implementation will result in a thrown error if there was no link to the first or current page, just like it would before since those methods would not exist on the class. Essentially this changes only the type of the error thrown: for example, instead of "TypeError: page.current is not a function" the client will get "Error: Missing link to the current page of results".

Users of the client library should not have expected the .first() and .current() methods to be optional before, as the public definition for PaginatedResult in ably.d.ts declares them as regular methods, thus this should not be a breaking change.

This makes internal PaginatedResult match the public one in ably.d.ts. This enables union types between internal and public APIs for PaginatedResult, which will be needed for the new Push device listSubscriptions API in #2013.

Summary by CodeRabbit

Summary by CodeRabbit

  • Refactor
    • Improved the reliability and consistency of paginated navigation controls, ensuring clearer behavior when navigating between pages of results.
    • Enhanced error handling for pagination actions, providing more informative feedback when navigation links are unavailable.

@VeskeR VeskeR requested a review from lawrence-forooghian May 1, 2025 01:00
Copy link

coderabbitai bot commented May 1, 2025

Walkthrough

The PaginatedResult class in the pagination library was refactored to replace dynamically assigned optional function properties with explicit method implementations. The class now uses a private property to manage pagination link parameters and provides clear, consistently named methods for navigation (first, current, next) and state checks (hasFirst, hasCurrent, hasNext, isLast). Error handling for missing pagination links is now standardized using the ErrorInfo class, and the interface for interacting with paginated results is more structured.

Changes

File(s) Change Summary
src/common/lib/client/paginatedresource.ts Refactored PaginatedResult class: removed optional function properties, added explicit navigation and state-check methods, standardized error handling, and introduced a private property for link parameters.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PaginatedResult

    Client->>PaginatedResult: first()
    alt Link exists
        PaginatedResult-->>Client: Promise<PaginatedResult>
    else Link missing
        PaginatedResult-->>Client: throw ErrorInfo
    end

    Client->>PaginatedResult: next()
    alt Next link exists
        PaginatedResult-->>Client: Promise<PaginatedResult>
    else No next link
        PaginatedResult-->>Client: null
    end

    Client->>PaginatedResult: isLast()
    PaginatedResult-->>Client: Boolean (not hasNext())
Loading

Possibly related issues

Poem

In fields of code, the pages turn,
With methods clear, no more to yearn.
No optional hops, just steady stride,
Through links and states, we now can glide.
If a link is lost, an error will show—
This rabbit’s pagination is ready to go!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between be5e457 and 45f51b2.

📒 Files selected for processing (1)
  • src/common/lib/client/paginatedresource.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/common/lib/client/paginatedresource.ts
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: test-node (20.x)
  • GitHub Check: test-browser (webkit)
  • GitHub Check: test-node (18.x)
  • GitHub Check: test-browser (firefox)
  • GitHub Check: test-browser (chromium)
  • GitHub Check: test-npm-package
  • GitHub Check: test-node (16.x)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot temporarily deployed to staging/pull/2021/bundle-report May 1, 2025 01:01 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/2021/features May 1, 2025 01:01 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/2021/typedoc May 1, 2025 01:01 Inactive
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/common/lib/client/paginatedresource.ts (2)

150-150: Consider using distinct error codes for different error scenarios.

Both error messages use the same error code (50000) and status code (500). For better error identification and troubleshooting, consider using distinct error codes for different error scenarios.

- throw new ErrorInfo('Missing link to the first page of results', 50000, 500);
+ throw new ErrorInfo('Missing link to the first page of results', 50001, 500);

- throw new ErrorInfo('Missing link to the current page of results', 50000, 500);
+ throw new ErrorInfo('Missing link to the current page of results', 50002, 500);

Also applies to: 158-158


147-147: Safe use of non-null assertion after existence check.

The non-null assertion operator (!) is used after checking for the existence of properties, which is safe in this context. However, consider that some linting configurations discourage its use. An alternative could be using optional chaining with a default value, though the current implementation is perfectly valid.

Also applies to: 155-155, 163-163

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d1eab0 and 68f4c30.

📒 Files selected for processing (1)
  • src/common/lib/client/paginatedresource.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/common/lib/client/paginatedresource.ts (1)
src/platform/web/index.ts (1)
  • ErrorInfo (48-48)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: test-node (20.x)
  • GitHub Check: test-browser (webkit)
  • GitHub Check: test-node (18.x)
  • GitHub Check: test-browser (firefox)
  • GitHub Check: test-node (16.x)
  • GitHub Check: test-browser (chromium)
  • GitHub Check: test-npm-package
🔇 Additional comments (8)
src/common/lib/client/paginatedresource.ts (8)

4-4: Good addition of the ErrorInfo import.

Adding the explicit import for ErrorInfo is appropriate since you're now using it in the refactored methods for standardized error handling.


137-137: Good encapsulation with private property.

Adding a private property to store the relParams is a good practice for encapsulation. This allows all the navigation methods to access the pagination link parameters consistently through a class property.


145-151: Clear implementation of first() method with proper error handling.

The implementation correctly checks for the existence of the first page link before attempting to navigate to it, and throws a descriptive error if the link is missing. This is more robust than the previous implementation which would result in a less specific TypeError.


153-159: Clear implementation of current() method with proper error handling.

Similar to the first() method, this implementation includes appropriate checks and error handling, which improves the developer experience when debugging issues with pagination.


161-167: Well-implemented next() method with appropriate null return.

The next() method correctly returns null when there is no next page, which is the expected behavior for paginated APIs and maintains compatibility with the previous implementation.


169-171: Good implementation of helper methods for checking link existence.

The hasFirst(), hasCurrent(), and hasNext() methods provide a clear and consistent way to check for the existence of pagination links. Using the 'in' operator is more explicit and safer than checking for truthiness.

Also applies to: 173-175, 177-179


181-183: Simple but effective isLast() implementation.

The isLast() method logically returns the negation of hasNext(), which is a clean way to determine if a page is the last one in the sequence.


145-183: Overall excellent refactoring of the PaginatedResult class.

The refactoring of the PaginatedResult class successfully replaces dynamically assigned optional function properties with explicit method implementations. This:

  1. Aligns with the public API declarations in ably.d.ts
  2. Provides better TypeScript type safety
  3. Improves error handling with descriptive messages
  4. Creates a more structured and maintainable codebase
  5. Enables union types between internal and public PaginatedResult APIs as needed for PR #2013

This implementation achieves the goals described in the PR objectives without introducing breaking changes for library users.

Base automatically changed from add-push-device-public-api to main May 1, 2025 08:26
return this.get(this._relParams!.first);
}

throw new ErrorInfo('Missing link to the first page of results', 50000, 500);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it should be 500 or any 5xx, we wrap client.request response into paginated result, and server doesn't guarantee that all requests are paginated, e.g. /time is not paginated. It's better to throw 4xx instead

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will check how client.request('/time') looks right now, it may help answer the null/error on missing page discussion below too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will change to "No link to the first page of results, 40400, 404"

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a side note re res.request() method. It wraps the response in HttpPaginatedResponse class, which is by the spec #HP2 should override the next() and first() calls so they return new empty HttpPaginatedResponse instance.
This is not the case currently in ably-js, as the internal HttpPaginatedResponse simply extends the PaginatedResult and suffers from the same null/missing link problems.
It feels like the whole paginated response handling in ably-js is a bit outdated. Created for this #2023

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@VeskeR VeskeR force-pushed the improve-paginated-result-api branch from 68f4c30 to 8d0b16d Compare May 1, 2025 09:18
@github-actions github-actions bot temporarily deployed to staging/pull/2021/features May 1, 2025 09:18 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/2021/typedoc May 1, 2025 09:18 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/2021/bundle-report May 1, 2025 09:19 Inactive
@VeskeR VeskeR force-pushed the improve-paginated-result-api branch from 8d0b16d to be5e457 Compare May 1, 2025 09:24
@github-actions github-actions bot temporarily deployed to staging/pull/2021/bundle-report May 1, 2025 09:24 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/2021/features May 1, 2025 09:24 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/2021/typedoc May 1, 2025 09:24 Inactive
This changes condition based function properties in the internal
`PaginatedResult` to regular class methods.

The spec TG5 [1] does not specify if the link to the first page (or
current) can be missing in the response and what should be done in such
case, so the new implementation is the best effort attempt to bring the
internal `PaginatedResult` API in line with the public API, while
keeping the same function behavior as before.

The new implementation will result in an thrown error if there was no
link to the first or current page, just like it would before since those
methods would not exist on the class. Essentially this changes only the
type of the error thrown: for example, instead of
"TypeError: page.current is not a function" the client will get
"Error: Missing link to the current page of results".

Users of the client library should not have expected the .first() and
.current() methods to be optional before, as the public definition
for `PaginatedResult` in ably.d.ts declares them as regular methods,
thus this should not be a breaking change.

This makes internal `PaginatedResult` match the public one in ably.d.ts.
This enables union types between internal and public APIs for
`PaginatedResult`, which will be needed for new Push device
listSubscriptions API in [2].

[1] https://sdk.ably.com/builds/ably/specification/main/features/#TG5
[2] #2013
@VeskeR VeskeR merged commit 4c99c7e into main May 1, 2025
12 of 14 checks passed
@VeskeR VeskeR deleted the improve-paginated-result-api branch May 1, 2025 14:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants