diff --git a/pkgs/shelf_router/CHANGELOG.md b/pkgs/shelf_router/CHANGELOG.md index 6e88703e..d07b2fbc 100644 --- a/pkgs/shelf_router/CHANGELOG.md +++ b/pkgs/shelf_router/CHANGELOG.md @@ -1,4 +1,6 @@ -## 1.1.5-wip +## 1.2.0-wip + +* Added function `getParams` to the `Router` class to get the parameters from a request * Require Dart `^3.3.0`. diff --git a/pkgs/shelf_router/lib/src/router.dart b/pkgs/shelf_router/lib/src/router.dart index 720d3c3e..f2bf7bba 100644 --- a/pkgs/shelf_router/lib/src/router.dart +++ b/pkgs/shelf_router/lib/src/router.dart @@ -190,6 +190,22 @@ class Router { return _notFoundHandler(request); } + /// Get URL parameters captured by the [Router]. + /// + /// Returns `null` if no parameters are captured. + Map? getParams(Request request) { + for (var route in _routes) { + if (route.verb != request.method.toUpperCase() && route.verb != 'ALL') { + continue; + } + var params = route.match('/${request.url.path}'); + if (params != null) { + return params; + } + } + return null; + } + // Handlers for all methods /// Handle `GET` request to [route] using [handler]. diff --git a/pkgs/shelf_router/test/router_test.dart b/pkgs/shelf_router/test/router_test.dart index fdffa51a..d932b129 100644 --- a/pkgs/shelf_router/test/router_test.dart +++ b/pkgs/shelf_router/test/router_test.dart @@ -86,6 +86,21 @@ void main() { expect(await get('/user/jonasfj/groups/42'), 'jonasfj / 42'); }); + test('get params via getParams', () async { + var app = Router(); + + app.get( + r'/user//groups/', + (Request request) => Response.ok(''), + ); + + final params = + app.getParams(Request('GET', Uri.http('', '/user/jonasfj/groups/42')))!; + + expect(params['user'], 'jonasfj'); + expect(params['group'], '42'); + }); + test('params by arguments', () async { var app = Router();