Skip to content

feat(router): Add support for setting up mappings of values on lookup router.use(path, map) - #186

Merged
nielsenko merged 6 commits into
serverpod:mainfrom
nielsenko:router-use
Oct 3, 2025
Merged

nielsenko merged 6 commits into
serverpod:mainfrom
nielsenko:router-use

Conversation

@nielsenko

@nielsenko nielsenko commented Oct 3, 2025 •

Copy link
Copy Markdown
Collaborator

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 as Handlers).

Includes tests covering basic transformation, composition, multiple HTTP methods, attached routers, and hierarchical middleware.

Related Issues

Fixes: #71

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 ///), 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

  • Includes breaking changes.
  • No breaking changes.

Summary by CodeRabbit

  • New Features
    • Adds route-level middleware allowing path-scoped transformations, composition of multiple middlewares, and hierarchical application across nested routers.
  • Tests
    • Adds comprehensive unit tests validating middleware composition, ordering, propagation to descendants, and interaction with attached routers.
  • Examples
    • Adds a runnable middleware example demonstrating auth middleware, request handling, and client-server interaction.

@coderabbitai

coderabbitai Bot commented Oct 3, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
Router middleware API
lib/src/router/router.dart
Adds public method void use(String path, T Function(T) map) which normalizes the path, composes per-path mappers, and wraps existing _RouterEntry values so transformed values are returned during lookup.
Tests for use()/middleware
test/router/router_use_test.dart
New comprehensive test suite covering root/specific-path uses, composition of multiple uses, ordering vs route registration, propagation to descendants, method-scoped behavior, attached-router interactions, and middleware-style wrapping across nested paths.
Middleware example
example/middleware_example.dart
New example demonstrating AuthMiddleware that validates a Bearer token, injects a user into request context, and a client request to /api/user/info; uses new middleware-style Router.use semantics.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning The pull request delivers a middleware registration method and comprehensive tests but does not implement the linked issue’s requirement for a fluent, chainable API (for example, enabling expressions like .get(...).with(logRequests)), so it only partially fulfills the objectives of issue #71. To fully comply with issue #71, extend the Router API to support chainable calls for route registration and middleware (such as returning the router instance from methods like use, get, or adding a .with alias), and include tests demonstrating fluent chaining.
Out of Scope Changes Check ⚠️ Warning The addition of example/middleware_example.dart introduces a standalone HTTP server example with an authentication middleware that is unrelated to the core Router.use feature and the objectives of issue #71, making it out of scope for this pull request. Consider moving the example to a separate documentation or example-focused pull request or clearly document it as supplementary material so that this PR remains focused on the middleware mapping implementation.
✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly describes the addition of middleware-style mapping support via router.use, succinctly highlighting the main feature added without extraneous details or noise.
Description Check ✅ Passed The pull request description follows the repository template by including a detailed description of the change, the related issue with proper “Fixes: #71” syntax, a completed pre-launch checklist, and a breaking changes section, matching the required structure and content.
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 3, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.85%. Comparing base (b1ed0fa) to head (8f367e7).
⚠️ Report is 1 commits behind head on main.

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.
📢 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-use branch 2 times, most recently from eb92170 to 2869fa7 Compare October 3, 2025 08:19
@nielsenko nielsenko self-assigned this Oct 3, 2025
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

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

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between b1ed0fa and 2869fa7.

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

Comment thread lib/src/router/router.dart Resolved
@nielsenko
nielsenko requested a review from a team October 3, 2025 08:52
@nielsenko
nielsenko marked this pull request as ready for review October 3, 2025 08:53
@nielsenko
nielsenko requested a review from SandPod October 3, 2025 09:15

@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 looks good, two questions.

Comment thread lib/src/router/router.dart Resolved
Comment thread test/router/router_use_test.dart Resolved
Comment thread lib/src/router/router.dart Resolved
@nielsenko
nielsenko requested a review from SandPod October 3, 2025 13:27

@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! But should the test be reworked as an example?

@nielsenko

Copy link
Copy Markdown
Collaborator Author

LGTM! But should the test be reworked as an example?

Reworked as example in 8f367e7

@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 3, 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: 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 the await on 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2869fa7 and 8f367e7.

📒 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.dart
  • test/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 _RouterEntry structure with growable: 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 AuthMiddleware class shows proper middleware structure:

  • Token extraction and validation (stub)
  • Context property storage
  • Handler wrapping and delegation

Note: _extractUser uses int.parse() which can throw FormatException. 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 User typedef, ContextProperty, and RequestContext extension 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 /api prefix. The route handler properly accesses the authenticated user via the context extension.

@nielsenko
nielsenko merged commit 8229ae3 into serverpod:main Oct 3, 2025
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.

Implement a concise, fluent API style for routing and middleware

2 participants