Skip to content

feat(router): Add asHandler extension to use Router<Handler> as Handler - #209

Merged
nielsenko merged 4 commits into
serverpod:mainfrom
nielsenko:router-as-handler
Oct 14, 2025
Merged

nielsenko merged 4 commits into
serverpod:mainfrom
nielsenko:router-as-handler

Conversation

@nielsenko

@nielsenko nielsenko commented Oct 10, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Adds asHandler extension to Router<Handler> to allow routers to be used directly as handlers without wrapping with routeWith. This simplifies common usage patterns when a router is the final handler in a pipeline.

The extension returns a handler that performs routing lookup and returns appropriate responses (404 for no match, 405 for method mismatch with Allow header).

Related Issues

Pre-Launch Checklist

  • This update focuses on a single feature or bug fix.
  • 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 ///).
  • 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

  • No breaking changes.

Additional Notes

Examples updated to demonstrate the new API pattern using router.asHandler instead of the more verbose Pipeline().addMiddleware(routeWith(router)).addHandler(...) pattern.

Summary by CodeRabbit

  • New Features

    • Routers can now be used directly as handlers with built-in 404/405 behavior.
  • Refactor

    • Examples simplified to use the new router-as-handler approach and Cascade-based fallbacks.
  • Tests

    • Added comprehensive routing tests covering params, methods (405/Allow), wildcards, nesting, middleware, and fallbacks.
  • Chores

    • CI workflow adjusted to temporarily continue-on-error for a score check and formatting tweaks.

@coderabbitai

coderabbitai Bot commented Oct 10, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Adds a Router.asHandler extension, updates examples to use router.asHandler with router-level middleware and Cascade 404 fallback, adds comprehensive router tests, and applies minor CI workflow tweaks (temporary continue-on-error for pana on stable and formatting/step version updates).

Changes

Cohort / File(s) Summary
CI workflow
.github/workflows/dart-tests.yaml
Temporarily marks the stable SDK "Check Pana Score" step non-fatal (continue-on-error: true) with a comment; bumps actions/setup-node in docs steps and applies indentation/formatting and minor step adjustments (no behavioral changes beyond the pana workaround).
Router API (new extension)
lib/src/middleware/routing_middleware.dart
Adds extension RouterHandler on Router<Handler> exposing Handler get asHandler which produces a Pipeline using routeWith(this) and a default 404 responder so a Router<Handler> can be used directly as a Handler.
Examples updated
example/example.dart, example/middleware_example.dart, example/multi_isolate.dart
Replace Pipeline+routeWith(router) patterns with router.asHandler; introduce router-level middleware via ..use('/', logRequests()); use Cascade with a 404 fallback for combined handler behavior.
Routing tests
test/router/router_handler_test.dart
Adds comprehensive tests for router.asHandler and routing behavior: matching, path params, 405 + Allow header, multi-method paths, 404, Cascade fallback, tail/wildcard segments, nested/matchedPath, empty-router 404, and middleware application; includes a fake Request helper.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant H as Router.asHandler (Handler)
  participant P as Pipeline
  participant RW as routeWith(router)
  participant R as Router
  participant F as Fallback 404

  Note over H,P: asHandler constructs Pipeline(routeWith(router)) with final 404 fallback
  C->>H: HTTP Request
  H->>P: handle(request)
  P->>RW: apply routing middleware & lookup
  RW->>R: perform route lookup
  alt route matched & method allowed
    R-->>RW: matched handler
    RW->>P: forward to handler
    P-->>C: 2xx/3xx/4xx response from handler
  else path matched but method not allowed
    R-->>RW: list of allowed methods
    RW-->>C: 405 with Allow header
  else no route match
    RW->>F: fall through
    F-->>C: 404 Not Found
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The modifications in the CI workflow file under .github/workflows/dart-tests.yaml, such as adding continue-on-error for the pana score step and bumping setup-node versions, fall outside the scope of the asHandler extension feature defined by issue #214 and are not referenced in the PR objectives. Consider extracting the CI workflow adjustments into a separate PR or clearly documenting their necessity to keep this feature PR focused solely on the asHandler extension functionality.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title concisely and accurately summarizes the primary change by indicating the addition of the asHandler extension for Router<Handler>, making it clear what feature is being introduced and aligning with the main focus of the changeset.
Linked Issues Check ✅ Passed The changes implement the asHandler extension exactly as outlined in issue #214 by exposing asHandler on Router<Handler>, performing routing lookup with correct 404 and 405 responses including the Allow header, and simplifying usage patterns with comprehensive tests validating the expected behavior.
Description Check ✅ Passed The pull request description follows the required template by including a detailed description, related issues reference, a completed pre-launch checklist, breaking changes section, and additional notes, providing all the necessary information for reviewers.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Oct 10, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.97%. Comparing base (922a5a7) to head (9a73a64).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #209      +/-   ##
==========================================
+ Coverage   91.90%   91.97%   +0.07%     
==========================================
  Files          85       85              
  Lines        3174     3177       +3     
  Branches     1639     1641       +2     
==========================================
+ Hits         2917     2922       +5     
+ Misses        257      255       -2     

☔ 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 force-pushed the router-as-handler branch 2 times, most recently from aaf8f99 to f60405a Compare October 10, 2025 16:28
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 11, 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.

@nielsenko
nielsenko requested a review from Copilot October 11, 2025 08:02

Copilot AI 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.

Pull Request Overview

This PR introduces an asHandler extension method for Router<Handler> to simplify router usage by allowing routers to be used directly as handlers without requiring explicit wrapping with routeWith. The extension provides standard HTTP response behaviors (404 for unmatched routes, 405 for method mismatches with Allow headers).

Key changes:

  • Adds RouterHandler extension with asHandler getter that wraps the router in a pipeline
  • Updates examples to demonstrate the new simplified API pattern
  • Adds comprehensive test coverage for the new functionality

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
lib/src/middleware/routing_middleware.dart Implements the RouterHandler extension with asHandler getter
test/router/router_handler_test.dart Comprehensive test suite covering routing scenarios, error responses, and middleware integration
example/example.dart Updated to use router.asHandler with Cascade for fallback handling
example/middleware_example.dart Simplified to use router.asHandler directly
example/multi_isolate.dart Updated to use router-based approach with asHandler
.github/workflows/dart-tests.yaml Added temporary workaround for pana score check
Comments suppressed due to low confidence (1)

lib/src/middleware/routing_middleware.dart:1

  • The documentation example references router.call but the actual implementation uses router.asHandler. The example should be updated to match the implementation.
import '../../relic.dart';

Comment thread example/example.dart Resolved

@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: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 922a5a7 and f60405a.

📒 Files selected for processing (6)
  • .github/workflows/dart-tests.yaml (2 hunks)
  • example/example.dart (1 hunks)
  • example/middleware_example.dart (1 hunks)
  • example/multi_isolate.dart (1 hunks)
  • lib/src/middleware/routing_middleware.dart (1 hunks)
  • test/router/router_handler_test.dart (1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.7)
.github/workflows/dart-tests.yaml

143-143: the runner of "actions/setup-node@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🔇 Additional comments (1)
example/example.dart (1)

16-24: Update comment to reference asHandler.

The comment still mentions the old call() extension, but the code now relies on router.asHandler. Please align the comment so newcomers aren’t misled.

-  // Router<Handler> can be used directly as a Handler via the call() extension.
+  // Router<Handler> can be used directly as a Handler via the asHandler extension.

Likely an incorrect or invalid review comment.

Comment thread .github/workflows/dart-tests.yaml Resolved
Adds a call() extension method convenience method to
Router<Handler>, allowing it to be used "directly" as a Handler without
wrapping with routeWith().
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit I know it is backwards, but please create matching issue for this PR

@coderabbitai

coderabbitai Bot commented Oct 11, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Create a GitHub issue for PR #209

gh issue create \
  --title "Add asHandler extension to Router<Handler> for simplified handler usage" \
  --body "## Description

This issue tracks the feature implemented in PR #209 to add an \`asHandler\` extension to \`Router<Handler>\`, enabling routers to be used directly as handlers without wrapping with \`routeWith\`.

## Feature Summary

- Adds an \`asHandler\` extension method to \`Router<Handler>\`
- Returns a handler that performs routing lookup
- Provides appropriate responses:
  - 404 when no route matches
  - 405 for method mismatch (includes \`Allow\` header)
- Simplifies common usage patterns where a router is the final handler in a pipeline

## Benefits

- Reduces boilerplate code
- More intuitive API for simple routing scenarios
- Maintains existing routing behavior while providing a cleaner interface

## Related PR

- Pull Request: #209

## Requester

@nielsenko

---

_Note: This issue was created after the PR was opened to provide tracking and documentation._"

Length of output: 45


@nielsenko: I've created issue #214 to track this feature. The issue includes a description of the asHandler extension, its benefits, and references back to this PR.

You can view the issue here: #214

@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 11, 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.

@nielsenko nielsenko self-assigned this Oct 11, 2025
@nielsenko
nielsenko marked this pull request as ready for review October 11, 2025 08:31

@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: 0

🧹 Nitpick comments (1)
example/example.dart (1)

9-24: Avoid double logRequests() middleware.

logRequests() is attached both on the router (Line 11) and on the surrounding Pipeline (Line 18), so matched requests are logged twice. Pick either the router-level middleware or the pipeline-level middleware to keep logging once.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f60405a and 9a73a64.

📒 Files selected for processing (6)
  • .github/workflows/dart-tests.yaml (2 hunks)
  • example/example.dart (1 hunks)
  • example/middleware_example.dart (1 hunks)
  • example/multi_isolate.dart (1 hunks)
  • lib/src/middleware/routing_middleware.dart (1 hunks)
  • test/router/router_handler_test.dart (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • .github/workflows/dart-tests.yaml
  • lib/src/middleware/routing_middleware.dart
  • test/router/router_handler_test.dart
  • example/middleware_example.dart
  • example/multi_isolate.dart

@nielsenko
nielsenko requested a review from a team October 11, 2025 08:32

@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.

Changes look good! Have one example question and one for my own knowledge.

Comment thread example/example.dart Resolved
@nielsenko
nielsenko requested a review from SandPod October 14, 2025 09:05

@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.

👍

@nielsenko
nielsenko merged commit ef24eec into serverpod:main Oct 14, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Oct 14, 2025
8 of 9 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Feb 17, 2026
7 of 8 tasks
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.

Add asHandler extension to Router<Handler> for simplified handler usage

3 participants