angel_route 3.0.6

  • Readme
  • Changelog
  • Example
  • Installing
  • 75

angel_route #

Pub build status

A powerful, isomorphic routing library for Dart.

This API is a huge improvement over the original Angel routing system, and thus deserves to be its own individual project.

angel_route exposes a routing system that takes the shape of a tree. This tree structure can be easily navigated, in a fashion somewhat similar to a filesystem. The Router API is a very straightforward interface that allows for your code to take a shape similar to the route tree. Users of Laravel and Express will be very happy.

angel_route does not require the use of Angel, and has minimal dependencies. Thus, it can be used in any application, regardless of framework. This includes Web apps, Flutter apps, CLI apps, and smaller servers which do not need all the features of the Angel framework.

Contents #

Examples #

Routing #

If you use Angel, every Angel instance is a Router in itself.


main() {
  final router = new Router();
  
  router.get('/users', () {});
  
  router.post('/users/:id/timeline', (String id) {});
  
  router.get('/square_root/:id([0-9]+)', (n) { 
    return { 'result': pow(int.parse(n), 0.5) };
  });
  
  // You can also have parameters auto-parsed.
  //
  // Supports int, double, and num.
  router.get('/square_root/int:id([0-9]+)', (int n) { 
      return { 'result': pow(n, 0.5) };
    });
  
  router.group('/show/:id', (router) {
    router.get('/reviews', (id) {
      return someQuery(id).reviews;
    });
    
    // Optionally restrict params to a RegExp
    router.get('/reviews/:reviewId([A-Za-z0-9_]+)', (id, reviewId) {
      return someQuery(id).reviews.firstWhere(
        (r) => r.id == reviewId);
    });
  }, middleware: [put, middleware, here]);
}

The default Router does not give any notification of routes being changed, because there is no inherent stream of URL's for it to listen to. This is good, because a server needs a lot of flexibility with which to handle requests.

Hierarchy #

main() {
  final router = new Router();
  
  router
    .chain('middleware1')
    .chain('other_middleware')
    .get('/hello', () {
      print('world');
    });
  
  router.group('/user/:id', (router) {
    router.get('/balance', (id) async {
      final user = await someQuery(id);
      return user.balance;
    });
  });
}

See the tests for good examples.

In the Browser #

Supports both hashed routes and pushState. The BrowserRouter interface exposes a Stream<RoutingResult> onRoute, which can be listened to for changes. It will fire null whenever no route is matched.

angel_route will also automatically intercept <a> elements and redirect them to your routes.

To prevent this for a given anchor, do any of the following:

  • Do not provide an href
  • Provide a download or target attribute on the element
  • Set rel="external"

Route State #

main() {
  final router = new BrowserRouter();
  // ..
  router.onRoute.listen((route) {
    if (route == null)
      throw 404;
    else route.state['foo'] = 'bar';
  });

  router.listen(); // Start listening
}

For applications where you need to access a chain of handlers, consider using onResolve instead. You can see an example in web/shared/basic.dart.

Route Parameters #

Routes can have parameters, as seen in the above examples. Use allParams in a RoutingResult to get them as a nice Map:

var router = new Router();
router.get('/book/:id/authors', () => ...);

var result = router.resolve('/book/foo/authors');
var params = result.allParams; // {'id': 'foo'};

3.0.6 #

  • Remove static default values for middleware.

3.0.5 #

  • Add MiddlewarePipelineIterator.

3.0.4 #

  • Add RouteResult class, which allows segments (i.e. wildcard) to modify the tail.
  • Add more wildcard tests.

3.0.3 #

  • Support trailing text after parameters with custom Regexes.

3.0.2 #

  • Support leading and trailing text for both :parameters and *

3.0.1 #

  • Make the callback in Router.group generically-typed.

3.0.0 #

  • Make Router and Route single-parameter generic.
  • Remove package:browser dependency.
  • BrowserRouter.on now only accepts a String.
  • MiddlewarePipeline.routingResults now accepts an Iterable<RoutingResult>, instead of just a List.
  • Removed deprecated Route.as, as well as Router.registerMiddleware.
  • Completely removed Route.requestMiddleware.

2.0.7 #

  • Minor strong mode updates to work with stricter Dart 2.

2.0.5 #

  • Patch to work with combinator@1.0.0.

example/main.dart

import 'dart:math';

import 'package:angel_route/angel_route.dart';

main() {
  final router = new Router();

  router.get('/whois/~:user', () {});

  router.get('/wild*', () {});

  router.get('/ordinal/int:n([0-9]+)st', () {});

  print(router.resolveAbsolute('/whois/~thosakwe').first.allParams);
  print(router.resolveAbsolute('/wild_thornberrys').first.route.path);
  print(router.resolveAbsolute('/ordinal/1st').first.allParams);

  router.get('/users', () {});

  router.post('/users/:id/timeline', (String id) {});

  router.get('/square_root/:id([0-9]+)', (String n) {
    return {'result': pow(int.parse(n), 0.5)};
  });

  // You can also have parameters auto-parsed.
  //
  // Supports int, double, and num.
  router.get('/square_root/int:id([0-9]+)', (int n) {
    return {'result': pow(n, 0.5)};
  });

  router.group('/show/:id', (router) {
    router.get('/reviews', (id) {
      return someQuery(id).reviews;
    });

    // Optionally restrict params to a RegExp
    router.get('/reviews/:reviewId([A-Za-z0-9_]+)', (id, reviewId) {
      return someQuery(id).reviews.firstWhere((r) => r.id == reviewId);
    });
  });
}

SomeQuery someQuery(id) => new SomeQuery();

class SomeQuery {
  List<SomeQueryReview> get reviews => [
        SomeQueryReview('fake'),
        SomeQueryReview('data'),
      ];
}

class SomeQueryReview {
  final String id;

  SomeQueryReview(this.id);
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  angel_route: ^3.0.6

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:angel_route/angel_route.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
66
Health:
Code health derived from static analysis. [more]
72
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
75
Learn more about scoring.

We analyzed this package on Nov 22, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.0
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:angel_route/angel_route.dart.

Health suggestions

Fix lib/src/router.dart. (-13.09 points)

Analysis of lib/src/router.dart reported 28 hints, including:

line 24 col 30: Unnecessary new keyword.

line 36 col 29: Unnecessary new keyword.

line 39 col 7: Unnecessary new keyword.

line 48 col 40: Unnecessary new keyword.

line 75 col 7: DO use curly braces for all flow control structures.

Fix lib/src/grammar.dart. (-5.84 points)

Analysis of lib/src/grammar.dart reported 12 hints, including:

line 7 col 21: Unnecessary new keyword.

line 10 col 20: Unnecessary new keyword.

line 14 col 11: Unnecessary new keyword.

line 43 col 13: Unnecessary new keyword.

line 44 col 33: Unnecessary new keyword.

Fix lib/browser.dart. (-4.89 points)

Analysis of lib/browser.dart reported 10 hints, including:

line 8 col 22: Unnecessary new keyword.

line 9 col 30: Unnecessary new keyword.

line 23 col 11: Unnecessary new keyword.

line 24 col 11: Unnecessary new keyword.

line 52 col 7: Unnecessary new keyword.

Fix additional 4 files with analysis or formatting issues. (-7.41 points)

Additional issues in the following files:

  • lib/src/route.dart (8 hints)
  • lib/src/routing_exception.dart (3 hints)
  • lib/src/routing_result.dart (3 hints)
  • lib/string_util.dart (1 hint)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev <3.0.0
combinator ^1.0.0 1.1.0
meta ^1.0.0 1.1.8
path ^1.0.0 1.6.4
string_scanner ^1.0.0 1.0.5
Transitive dependencies
charcode 1.1.2
code_buffer 1.0.1
matcher 0.12.6
quiver 2.1.2+1
source_span 1.5.5
stack_trace 1.9.3
term_glyph 1.1.0
tuple 1.0.3
Dev dependencies
build_runner ^0.10.0
build_web_compilers ^0.4.0
http >=0.11.3 <0.12.0
pedantic ^1.0.0
test ^1.0.0