Giter Site home page Giter Site logo

angel-dart-archive / route Goto Github PK

View Code? Open in Web Editor NEW
12.0 3.0 5.0 129 KB

moved to angel-dart/angel/packages/route

Home Page: https://github.com/angel-dart/angel/tree/master/packages/route

License: MIT License

Dart 96.44% HTML 3.56%
angel dart angel-framework isomorphic router routing

route's Introduction

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 = 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]);

  // Grouping can also take async callbacks.
  await router.groupAsync('/hello', (router) async {
    var name = await getNameFromFileSystem();
    router.get(name, (req, res) => '...');
  });
}

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 = 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 = 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 = Router();
router.get('/book/:id/authors', () => ...);

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

route's People

Contributors

thosakwe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

route's Issues

_printDebug leaks a bit

Now resolving GET "/google", absolute: auth/google
Path segments: [google]
Could not resolve path "/google".

Segments

Would fix a lot

/user/:id should build two routes, not one :)

Flutter Web

Does this support Flutter Web or just any web app ? Not clear from readme

Some working example dart-lang

It's possibile see any explicit example with 2 button that change route in website?
How angel-dart call HTML when click on specific button.
Thanks Sorry for the issue

Groups and mount

Group needs to call mount, and mount needs to modify matchers, otherwise params are not parsed

I always get 'Cannot resolve route for link param...'

Hi, my config looks like this:

main() {
    ...
    final router = new BrowserRouter(hash: true);
    _configRouter(router);
   ...
}

void _configRouter(final BrowserRouter router ) {
    configLogging(show: Level.INFO);
    
    final Logger _logger = new Logger('main.configRouter');

    router.onResolve.listen((result) {
        final route = result?.route;
        if (route == null) {
            _logger.shout('No Active Route');
        } else {
            _logger.shout('Active Route: ${route.name ?? route.path}');
        }
    });
    
    router.get("/test", () {
        print("/Test.html");
        
        _logger.info("/Test.html");
    });

    router.get("test", () {
        print("Test.html");

        _logger.info("Test.html");
    });

    router.get("/#/test2", () {
        _logger.info("Test2.html");
    });

    router..dumpTree()..listen(); // Start listening
}

My links

<a href="/test">Test</a> | <a href="/#/test2">Test II</a>

But I geht either Cannot resolve route for link param "test" for the first link or Cannot resolve route for link param "#" for the second link

Any ideas?

Add mountAsync, groupAsync

These will do the same as their sync equivalents, but allow for a callback that returns FutureOr<void>.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.