Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support mounting dynamic routes. FIxes #250 #288

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Prev Previous commit
Next Next commit
some comments
  • Loading branch information
davidmartos96 committed Sep 15, 2022
commit c1378fc647e8cec95af2b73dded8ca8360e77371
21 changes: 15 additions & 6 deletions pkgs/shelf_router/lib/src/router.dart
Original file line number Diff line number Diff line change
Expand Up @@ -197,23 +197,32 @@ class Router {
Future<Response> _invokeMountedHandler(
Request request, Function handler, List<String> pathParams) async {
final paramsMap = request.params;
final effectivePath = _replaceParamsInPath(request.url.path, paramsMap);

return await Function.apply(handler, [
request.change(path: effectivePath),
...pathParams.map((param) => paramsMap[param]),
]) as Response;
}

/// Replaces the variable slots (<someVar>) from [path] with the
/// values from [paramsMap]
String _replaceParamsInPath(
String urlPath,
Map<String, String> paramsMap,
) {
final pathParamSegment = paramsMap[_kRestPathParam];
final urlPath = request.url.path;
late final String effectivePath;
if (pathParamSegment != null && pathParamSegment.isNotEmpty) {
/// If we encounter the "rest path" parameter we remove it
/// from the request path that shelf will handle.
effectivePath =
urlPath.substring(0, urlPath.length - pathParamSegment.length);
} else {
// No parameters in the requested path
effectivePath = urlPath;
}

return await Function.apply(handler, [
request.change(path: effectivePath),
...pathParams.map((param) => paramsMap[param]),
]) as Response;
return effectivePath;
}

/// Route incoming requests to registered handlers.
Expand Down