flatten<T> function

Router<T> flatten <T>(Router<T> router)

Optimizes a router by condensing all its routes into one level.

Implementation

Router<T> flatten<T>(Router<T> router) {
  var flattened = new Router<T>();

  for (var route in router.routes) {
    if (route is SymlinkRoute<T>) {
      var base = route.path.replaceAll(_straySlashes, '');
      var child = flatten(route.router);

      for (var route in child.routes) {
        var path = route.path.replaceAll(_straySlashes, '');
        var joined = '$base/$path'.replaceAll(_straySlashes, '');
        flattened.addRoute(route.method, joined.replaceAll(_straySlashes, ''),
            route.handlers.last,
            middleware:
                route.handlers.take(route.handlers.length - 1).toList());
      }
    } else {
      flattened.addRoute(route.method, route.path, route.handlers.last,
          middleware: route.handlers.take(route.handlers.length - 1).toList());
    }
  }

  return flattened..enableCache();
}