Skip to content

feat: The routeWith middleware builder function is now generic. - #78

Merged
nielsenko merged 2 commits into
mainfrom
routing-generic
May 26, 2025
Merged

nielsenko merged 2 commits into
mainfrom
routing-generic

Conversation

@nielsenko

@nielsenko nielsenko commented May 22, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This pull request introduces a feature that makes the routeWith middleware builder function generic.
You can pass any Router as long as you also pass a toHandler function that tells the middleware how
to produce a handler from a stored route.

Key changes:

  • The routeWith function in lib/src/middleware/routing_middleware.dart now accepts a generic Router<T> and an optional toHandler function to convert T to a Handler.
  • If T is already a Handler (or a subtype), and no toHandler is provided, it will be automatically cast.
  • Tests in test/middleware/routing_middleware_test.dart were updated to reflect this change, specifically by parameterizing Router as Router<Handler>().

Related Issues

  • Closes: ?

Pre-Launch Checklist

Please ensure that your PR meets the following requirements before submitting:

  • This update focuses on a single feature or bug fix. (For multiple fixes, please submit separate PRs.)
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

Signature of routeWith changes.

Summary by CodeRabbit

  • Refactor

    • Improved routing middleware to support routers with any handler type, providing greater flexibility for advanced routing scenarios.
  • Tests

    • Updated tests to align with the new routing middleware enhancements.

@coderabbitai

coderabbitai Bot commented May 22, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

The routing middleware was refactored to be generic over any handler type, not just Handler. The routeWith function now accepts routers of any type and an optional conversion function. The internal middleware builder was renamed and made generic, with type checks and conversion logic added. Related test code was updated for type specificity.

Changes

File(s) Change Summary
lib/src/middleware/routing_middleware.dart Refactored routing middleware to be generic over handler type T, added conversion logic, replaced RoutingMiddleware with _RoutingMiddlewareBuilder<T>, and updated routeWith signature. Added runtime type checking helper.
test/middleware/routing_middleware_test.dart Updated test to instantiate Router<Handler> instead of raw Router().

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant Router
    participant Handler

    Client->>Middleware: Send request
    Middleware->>Router: Match route
    Router-->>Middleware: Return matched value of type T
    Middleware->>Middleware: Convert T to Handler (using toHandler or cast)
    Middleware->>Handler: Invoke handler
    Handler-->>Middleware: Return response
    Middleware-->>Client: Return response
Loading

Possibly related PRs

  • feat: Router middleware #68: Introduced the original routing middleware fixed to Router<Handler> and the RoutingMiddleware class, which this PR generalizes and refactors.

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.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 docstrings to generate docstrings for this 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.

@codecov

codecov Bot commented May 22, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.47%. Comparing base (1730a54) to head (439d6ce).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #78      +/-   ##
==========================================
+ Coverage   82.42%   82.47%   +0.05%     
==========================================
  Files          80       80              
  Lines        2429     2436       +7     
  Branches     1362     1367       +5     
==========================================
+ Hits         2002     2009       +7     
  Misses        427      427              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nielsenko nielsenko self-assigned this May 22, 2025
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 22, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
test/middleware/routing_middleware_test.dart (1)

25-28: 🛠️ Refactor suggestion

Add a test that exercises the new generic + toHandler path

All updated tests still use Router<Handler> where the automatic cast branch
is taken. To guard against regressions in the _toHandler initialisation
logic, add a test like:

final strRouter = Router<String>()..add(Method.get, '/', (_) => 'ok');
final mw = routeWith<String>(
  strRouter,
  toHandler: (s) => respondWith((_) => Response.ok(s)),
);

final ctx = _FakeRequest('/').toContext(Object());
final resCtx = await mw(respondWith((_) => Response.notFound()))(ctx)
    as ResponseContext;

expect(resCtx.response.statusCode, 200);
expect(await resCtx.response.readAsString(), 'ok');

This will fail with the current bug and pass once the fix above is applied.

🧹 Nitpick comments (2)
lib/src/middleware/routing_middleware.dart (2)

32-33: Consider switching from url to requestUri to preserve full path & query

The TODO comment hints at this; using Request.url drops the leading slash and
can mis-handle .. segments or empty paths. Request.requestUri (or
Request.requestedUri depending on the framework version) preserves the raw
requested string, including query parameters, and avoids subtle mismatches
during router lookup.


56-57: _isSubtype helper works but is brittle with NNBD future changes

The (<S>[] is List<T>) trick is idiomatic but relies on list‐covariance and
can break if the language alters that rule. A safer (though slightly slower)
alternative is typeOf<S>() is Type checks via dart:mirrors or, when mirrors
are unavailable, simply defaulting to the cast path and letting it fail fast.
Not a blocker, just be aware of the limitation.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1730a54 and da239b1.

📒 Files selected for processing (2)
  • lib/src/middleware/routing_middleware.dart (2 hunks)
  • test/middleware/routing_middleware_test.dart (1 hunks)

You can pass any Router<T> as long as you also pass a toHandler function
that tells the middleware how to produce a handler from a stored route.
@nielsenko
nielsenko marked this pull request as ready for review May 23, 2025 04:59
@nielsenko
nielsenko requested a review from SandPod May 23, 2025 04:59

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants