getParamsPath method

(String, Map<String, Object?>) getParamsPath(
  1. String clientPath,
  2. String serverPath
)

Extracts URL parameters from route patterns and matches them with request paths.

This method performs pattern matching between a client's requested path and a server-defined route pattern that contains parameter placeholders. It supports dynamic URL segments defined with curly braces (e.g., {id}, {slug}).

The matching process:

  1. Compares path segment counts (must be equal)
  2. Identifies parameter placeholders in the route pattern
  3. Extracts corresponding values from the client path
  4. Builds a parameter map with extracted values

clientPath The actual path from the incoming HTTP request serverPath The route pattern with parameter placeholders (e.g., /users/{id}/posts/{slug})

Returns a record containing:

  • $1: The processed server path with placeholders replaced by actual values
  • $2: A map of parameter names to their extracted values

Example:

final result = getParamsPath('/users/123/posts/hello-world', '/users/{id}/posts/{slug}');
// result.$1 = '/users/123/posts/hello-world'
// result.$2 = {'id': '123', 'slug': 'hello-world'}

Implementation

(String, Map<String, Object?>) getParamsPath(
  String clientPath,
  String serverPath,
) {
  String resultKey = serverPath;
  Map<String, Object?> resultParams = {};

  var serverUri = Uri(path: serverPath);
  var clientUri = Uri(path: clientPath);

  if (serverUri.pathSegments.length != clientUri.pathSegments.length) {
    return (resultKey, resultParams);
  }

  for (int i = 0; i < clientUri.pathSegments.length; i++) {
    var key = Uri.decodeFull(serverUri.pathSegments[i]);
    if (!key.startsWith("{") || !key.endsWith("}")) {
      continue;
    } else {
      key = key.replaceAll("{", "").replaceAll("}", "");
      resultKey = resultKey.replaceFirst("{$key}", clientUri.pathSegments[i]);
      resultParams[key] = clientUri.pathSegments[i];
    }
  }

  return (resultKey, resultParams);
}