Repository navigation
feat(router): Add fallback property for unmatched routes - #196
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughSwitches examples/tests from Pipeline-based composition to using Router as a direct handler, adds a nullable Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor C as Client
participant S as Server
participant R as Router<Handler>
participant H as MatchedHandler
participant F as FallbackHandler
C->>S: HTTP request
S->>R: router.call(ctx)
alt path & method match
R->>R: set matchedPath / pathParameters / remainingPath
R->>H: invoke(ctx)
H-->>R: response
R-->>S: response (e.g., 200)
else path matched but method not allowed
R-->>S: 405 Method Not Allowed + Allow header
else path miss
alt fallback set
R->>F: invoke(ctx)
F-->>R: response (custom or 404)
R-->>S: response
else no fallback
R-->>S: 404 Not Found
end
end
note right of R: RequestContextEx exposes matchedPath, pathParameters, remainingPath
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
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 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #196 +/- ##
=======================================
Coverage 91.90% 91.90%
=======================================
Files 86 86
Lines 3248 3248
Branches 1666 1666
=======================================
Hits 2985 2985
Misses 263 263 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
d678367 to
afbdc04
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
lib/src/middleware/routing_middleware.dart (1)
71-81: Constructor can throw LateInitializationError; throw ArgumentError instead.if T is not Handler and toHandler is null,
_toHandlerremains uninitialized and reading it inArgumentError.checkNotNull(_toHandler, ...)triggers a LateInitializationError, not a clear ArgumentError. Initialize or explicitly throw.Apply this diff:
_RoutingMiddlewareBuilder( this._router, { final Handler Function(T)? toHandler, }) { if (toHandler != null) { _toHandler = toHandler; } else if (_isSubtype<T, Handler>()) { _toHandler = (final x) => x as Handler; - } - ArgumentError.checkNotNull(_toHandler, 'toHandler'); + } else { + throw ArgumentError( + 'toHandler must be provided when T is not a Handler.', + ); + } }
🧹 Nitpick comments (2)
test/router/router_handler_test.dart (1)
18-316: Solid coverage, behavior matches design.Tests exercise 404/405, fallback, params, wildcards, matched/remaining paths, middleware. Looks good. Consider adding one routeWith-based test to assert PathMiss delegates to next (to lock BC for pipeline usage).
lib/src/middleware/routing_middleware.dart (1)
87-94: Minor duplication: centralize 405 response creation.The 405 construction is duplicated in routeWith and RouterHandler.call. Extract a small helper to avoid drift.
Example outside-diff addition:
static FutureOr<HandledContext> _respond405( RequestContext ctx, Iterable<Method> allowed, ) => ctx.respond( Response(405, headers: Headers.build((h) => h.allow = allowed)), );Then replace both sites with
_respond405(ctx, result.allowed).Also applies to: 187-193
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
README.md(1 hunks)example/example.dart(1 hunks)example/middleware_example.dart(2 hunks)example/multi_isolate.dart(1 hunks)lib/src/middleware/routing_middleware.dart(4 hunks)lib/src/router/router.dart(1 hunks)test/middleware/routing_middleware_test.dart(3 hunks)test/router/router_handler_test.dart(1 hunks)test/static/create_file_handler_test.dart(2 hunks)test/static/mounted_test.dart(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-22T07:34:15.403Z
Learnt from: CR
PR: serverpod/relic#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-22T07:34:15.403Z
Learning: Applies to {lib,example}/**/*.dart : Implement handlers as functions processing RequestContext and returning ResponseContext; use middleware to wrap handlers and compose via a pipeline
Applied to files:
example/multi_isolate.dartexample/middleware_example.dartexample/example.dart
🔇 Additional comments (10)
lib/src/router/router.dart (1)
47-62: Well-designed fallback mechanism with clear documentation.The nullable
fallbackfield is properly typed and the documentation clearly explains:
- When it applies (path miss/404) vs when it doesn't (method miss/405)
- Composition behavior (only top-most fallback is used)
- Typical usage pattern via example
This design allows users to explicitly set or unset the fallback, and the distinction between path and method misses is important for proper HTTP semantics.
example/example.dart (1)
8-17: Clear demonstration of the new router-based pattern.The example effectively showcases:
- Inline middleware composition via
Router.use()- Centralized 404 handling via
Router.fallback- Direct router invocation via
router.callThe explanatory comments help users understand the benefits of this approach over Pipeline/Cascade composition.
example/multi_isolate.dart (1)
31-37: LGTM! Consistent adoption of router.call pattern.The multi-isolate example correctly demonstrates the new router-based serving approach, consistent with other examples in the codebase.
test/middleware/routing_middleware_test.dart (3)
231-233: LGTM! Tests correctly adopt router-level fallback.The nested routing test now uses
mainRouter.fallbackfor 404 handling andmainRouter.callas the handler, replacing the previous Pipeline-based approach while maintaining the same test assertions and coverage.
274-276: LGTM! Multi-level attachment test updated consistently.The test correctly demonstrates router.call usage with fallback for deeply nested routing scenarios, ensuring parameters are properly captured across multiple levels.
311-313: LGTM! Repeated parameter test uses new pattern.The test for repeated parameters across nested routers correctly adopts the router.call pattern with router-level fallback.
example/middleware_example.dart (1)
14-21: LGTM! Middleware example demonstrates path-specific middleware.The example clearly shows how to apply middleware to specific routes using
Router.use('/api', AuthMiddleware().call)and serves viarouter.call, demonstrating the new pattern for composing middleware.test/static/mounted_test.dart (1)
24-27: LGTM! Static handler test updated to router.call pattern.The test correctly adopts the router-level fallback and router.call as the handler, maintaining test coverage while using the new recommended approach.
test/static/create_file_handler_test.dart (1)
27-35: LGTM! File handler tests consistently use router.call pattern.All test cases have been updated to use
Router<Handler>with router-level fallback instead of Pipeline-based composition, maintaining the same test coverage and behavior.README.md (1)
46-54: LGTM! README updated to showcase the new router pattern.The example code has been updated to demonstrate the recommended approach using
Router<Handler>with inline middleware viause(), centralized 404 handling viafallback, and direct serving viarouter.call. This provides clear guidance for users adopting the framework.
There was a problem hiding this comment.
Pull Request Overview
This PR adds fallback functionality to the Router class and enables Router to be used directly as a Handler. The changes provide a more convenient API for handling unmatched routes (404s) and eliminate the need for Pipeline/Cascade composition in common scenarios.
- Added
Router.fallbackproperty for handling unmatched routes - Added
RouterHandler.call()extension allowingRouter<Handler>to be used directly as aHandler - Updated documentation and examples to prefer the new Router-based API over Pipeline composition
Reviewed Changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| lib/src/router/router.dart | Added fallback property with documentation |
| lib/src/middleware/routing_middleware.dart | Added RouterHandler extension and comprehensive documentation |
| test/router/router_handler_test.dart | Added comprehensive test suite for new router handler functionality |
| test/static/mounted_test.dart | Updated to use router.fallback and router.call |
| test/static/create_file_handler_test.dart | Refactored tests to use new router API |
| test/middleware/routing_middleware_test.dart | Updated tests to use router.fallback and router.call |
| example/example.dart | Updated main example to demonstrate router.use and router.fallback |
| example/middleware_example.dart | Simplified example using router.call |
| example/multi_isolate.dart | Updated to use router-based approach |
| README.md | Updated documentation to show preferred router-based API |
afbdc04 to
347b790
Compare
SandPod
left a comment
There was a problem hiding this comment.
Functionality looks great! Glad to see the usage of the package being simplified.
I have a suggestion regarding creating a more self-documenting API. Let me know what you think.
382339b to
bcb5abf
Compare
95f6a69 to
39547f1
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
39547f1 to
4d66f69
Compare
fdee670 to
6c2a5b3
Compare
|
This is stacked on top of #209. Please review that first |
Adds a fallback property to Router<T> that is called when no route
matches a request path (404, not 405). This provides a simpler
alternative to using Pipeline or Cascade for basic fallback scenarios.
Example usage:
final router = Router<Handler>()
..get('/users', usersHandler)
..fallback = notFoundHandler;
…stContextEx Improves documentation for routing middleware: - Adds detailed doc comments for routeWith() function - Documents behavior for path miss (calls next) vs method miss (returns 405) - Provides examples for Router<Handler> and custom types - Documents toHandler parameter usage - Adds comprehensive docs for RequestContextEx extension properties - Explains matchedPath, pathParameters, and remainingPath with examples - Notes relationship with RouterHandler.call extension
…llback over Pipeline/Cascade
…k instead of Cascade
6c2a5b3 to
51d210d
Compare
SandPod
left a comment
There was a problem hiding this comment.
Nice! One comment to fix otherwise it looks good, feel free to close when resolved.
Description
Router.fallbackproperty for handling unmatched routes (default to 404).RouterHandler.asHandlerextension onRouter<Handler>allowing it to be used directly as aHandler.Router.use()andRouter.fallbackoverPipelineandCascadecompositionThis provides a more direct API for common routing scenarios while maintaining backward compatibility with existing middleware patterns.
Related Issues
Fixes: #197
Pre-Launch Checklist
///), ensuring consistency with existing project documentation.Breaking Changes
All changes are additive. Existing
PipelineandCascadepatterns continue to work.Additional Notes
The
Router.fallbackproperty only applies to path misses (404). Method misses (405) still return the appropriate response withAllowheader as before.Summary by CodeRabbit