Repository navigation
feat(router): Add support for setting up mappings of values on lookup router.use(path, map) - #186
Conversation
📝 WalkthroughWalkthroughAdds Router.use(path, map) to register per-path value transformers that wrap route entries during lookup; adds unit tests validating middleware composition, scoping, ordering, and interactions with attached routers; introduces an example demonstrating middleware-based auth injection. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Dev as Developer
participant R as Router<T>
participant PT as PathTrie
participant E as _RouterEntry
Note over Dev,R: Register middleware and routes
Dev->>R: use(path, map)
R->>R: store/compose mapper for path
Dev->>R: add route / attach routers
R->>PT: insert(route entry)
Note over Dev,R: Lookup / request time
Dev->>R: lookup(method, path)
R->>PT: match(path)
PT-->>R: matched entry E
R->>R: collect composed mappers root→leaf
R->>E: wrap/transform entry value with composed mapper
E-->>Dev: returned transformed value / handler
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ 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 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #186 +/- ##
==========================================
+ Coverage 91.84% 91.85% +0.01%
==========================================
Files 85 85
Lines 3150 3155 +5
Branches 1627 1630 +3
==========================================
+ Hits 2893 2898 +5
Misses 257 257 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
eb92170 to
2869fa7
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
lib/src/router/router.dart (1)
65-75: Implementation is correct; TODO notes a valid optimization.The implementation correctly:
- Normalizes the path before delegation
- Preserves null entries for methods without routes
- Applies the transformation only to non-null values
- Creates a new immutable list to avoid mutation
The TODO comment at lines 66-68 identifies a performance optimization: currently all method entries are transformed eagerly, even though only one will be looked up. This is a minor efficiency concern that can be addressed later without affecting correctness.
The TODO optimization could defer transformation until the specific method is requested during lookup, avoiding unnecessary work. However, this would require refactoring the lookup path to compose transformations lazily.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
lib/src/router/router.dart(1 hunks)test/router/router_use_test.dart(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
- GitHub Check: Run Unit Tests (macos-latest, 3.5.0, downgrade)
- GitHub Check: Run Unit Tests (macos-latest, 3.5.0, upgrade)
- GitHub Check: Run Unit Tests (macos-latest, beta, upgrade)
- GitHub Check: Run Unit Tests (macos-latest, stable, upgrade)
- GitHub Check: Run Unit Tests (macos-latest, beta, downgrade)
- GitHub Check: Run Unit Tests (macos-latest, stable, downgrade)
- GitHub Check: Run Unit Tests (windows-latest, 3.5.0, upgrade)
🔇 Additional comments (1)
test/router/router_use_test.dart (1)
1-156: Excellent test coverage and correct expectations.The test suite comprehensively validates the
use()middleware functionality:
- Transformation semantics: Correctly tests that transformations compose leaf-to-root during lookup (tests at lines 18-28, 108-123, 125-138)
- Scoping: Validates path-scoped transformations affect only descendants (lines 58-73, 89-106)
- Method coverage: Confirms use applies to all HTTP methods at a path (lines 75-87)
- Ordering independence: Tests use before and after route definitions (lines 30-39)
- Router composition: Validates behavior across attached routers (lines 89-106, 108-123)
- Middleware pattern: Demonstrates correct root-to-leaf execution order for function values (lines 140-155)
All test expectations correctly reflect the composition order described in the PR: transformations apply leaf-to-root at lookup time, resulting in root-to-leaf execution order for handler functions.
SandPod
left a comment
There was a problem hiding this comment.
Changes looks good, two questions.
SandPod
left a comment
There was a problem hiding this comment.
LGTM! But should the test be reworked as an example?
Reworked as example in 8f367e7 |
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
example/middleware_example.dart (1)
11-40: Example demonstrates the pattern well.The server lifecycle is acceptable for demonstration purposes:
- Client request completes before
server.kill()due to theawaiton line 30- Cleanup is present, though abrupt
For production use, consider graceful shutdown with proper cleanup delays and error handling.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
example/middleware_example.dart(1 hunks)lib/src/router/router.dart(1 hunks)test/router/router_use_test.dart(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-10-03T08:29:41.559Z
Learnt from: nielsenko
PR: serverpod/relic#186
File: lib/src/router/router.dart:60-64
Timestamp: 2025-10-03T08:29:41.559Z
Learning: In the Router class in lib/src/router/router.dart, the use() method stores transformation functions on trie nodes. These functions are composed and applied during lookup (in PathTrie.lookup() at line 405), but the original stored route values are never modified. The transformation is temporary and only affects the returned value from lookup operations.
Applied to files:
lib/src/router/router.darttest/router/router_use_test.dart
📚 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/middleware_example.dart
🔇 Additional comments (13)
lib/src/router/router.dart (1)
60-72: LGTM! Clean middleware integration.The
use()method implementation is well-structured:
- Correctly normalizes the path before delegation
- Properly transforms non-null route entries while preserving nulls
- Maintains
_RouterEntrystructure withgrowable: false- Doc comment accurately describes lookup-time transformation behavior (as clarified in past review)
The implementation integrates cleanly with the existing routing infrastructure.
Based on learnings: transformations apply during lookup without modifying stored values.
test/router/router_use_test.dart (9)
5-14: LGTM! Basic transformation test is solid.This test correctly validates that a
use()call at root transforms the route value during lookup.
16-26: LGTM! Composition test validates leaf-to-root transformation order.This test correctly demonstrates that multiple
use()calls compose with leaf-to-root application order:(1 + 3) * 2 = 8.
28-37: LGTM! Order-independence test is valuable.This test validates that
use()can be called before routes are added, demonstrating that the middleware system doesn't depend on registration order.
39-54: LGTM! Descendant propagation test is thorough.This test correctly validates that a
use()at root transforms all descendant routes, verifying the hierarchical scope of middleware.
56-71: LGTM! Path-specific scoping test is precise.This test validates that middleware scope is correctly limited to the specified path and its descendants, leaving other routes unaffected.
73-85: LGTM! Multi-method transformation test is comprehensive.This test correctly validates that
use()transforms routes for all HTTP methods at the specified path, as expected from the implementation.
87-104: LGTM! Attached router transformation test is accurate.This test validates that
use()correctly scopes to attached sub-routers, transforming only routes under the attachment prefix.
106-121: LGTM! Cross-router composition test is well-designed.This test validates that
use()calls compose correctly when routers are attached, maintaining proper leaf-to-root transformation order across router boundaries.
138-153: LGTM! Excellent demonstration of middleware call order.This test elegantly validates that while transformations compose leaf-to-root (as noted in line 126), the resulting wrapped functions execute root-to-leaf. The output
<a><b><c>request</c></b></a>correctly shows the outermost middleware (/a) executing first, wrapping the inner layers.This is the expected and desirable behavior for middleware chains.
example/middleware_example.dart (3)
49-65: Middleware implementation demonstrates the pattern correctly.The
AuthMiddlewareclass shows proper middleware structure:
- Token extraction and validation (stub)
- Context property storage
- Handler wrapping and delegation
Note:
_extractUserusesint.parse()which can throwFormatException. In production code, validate the token format in_validate()before parsing, or wrap the parse in try-catch. For this example, the simplification is acceptable since it's clearly marked as illustrative.
42-47: LGTM! Context property pattern is well-demonstrated.The
Usertypedef,ContextProperty, andRequestContextextension show the proper pattern for storing and accessing authenticated user data in request contexts.
14-20: LGTM! Router middleware integration is clean.The router setup correctly demonstrates the
use()method for applying authentication middleware to the/apiprefix. The route handler properly accesses the authenticated user via the context extension.
Description
Adds
Router.use()method to support middleware-style transformations of routes. The method applies a mapping function to all routes under a given path prefix. Transformations compose hierarchically and are applied during lookup leaf-to-root, with execution order from root-to-leaf in the case of functions (such asHandlers).Includes tests covering basic transformation, composition, multiple HTTP methods, attached routers, and hierarchical middleware.
Related Issues
Fixes: #71
Pre-Launch Checklist
///), ensuring consistency with existing project documentation.Breaking Changes
Summary by CodeRabbit