addRoute method

Router addRoute(
  1. Route route
)

Add a route either to this router routes list or to the current execution stack

Implementation

Router addRoute(Route route) {
  if (_useRouteLater) {
    // only add route to _routes when in later use.
    // it will be added to the current stack when apply() is called
    // from app.use(path, router);
    _routes = [..._routes, route];
  } else {
    String pathId = combinePath(_basePath, '/:id');
    bool standardPath = route.path == _basePath || route.path == '/:id';

    // find index of route GET '/:id' in this router
    int index = _app.routes
        .indexWhere((r) => r.method == Method.get && r.path == pathId);

    // This is related to the process of adding standard Controller routes
    // defined in app.route() method (app.dart lines 476 - 481).
    //
    // Insert the additional route to the index before route get '/:id'
    // so it won't be mistakenly recognised as route '/:id'
    //
    // For example, when we want to add route GET /user/vip into /user
    // it can be mistakenly recognised by route /user/:id
    // as a user with id = vip
    //
    // That's why all route /:id should be put in the last.
    //
    // If index == -1, it means there're no standard routes before,
    // so it's safe to use _app.addRoute()
    //
    if (!standardPath && index != -1) {
      _app.insertRoute(
          index,
          Route(
              method: route.method,
              path: combinePath(_basePath, route.path),
              middleware: route.middleware,
              callback: route.callback));
    } else {
      _app.addRoute(Route(
        method: route.method,
        path: combinePath(_basePath, route.path),
        middleware: route.middleware,
        callback: route.callback,
      ));
    }
  }

  return this;
}