shelf_route 0.1.0 copy "shelf_route: ^0.1.0" to clipboard
shelf_route: ^0.1.0 copied to clipboard

outdatedDart 1 only

A sample command-line application

Router for Dart Shelf #

Introduction #

Provides Shelf middleware for defining routes.

Shelf Route makes it easy to define routes in a modular way. How?

  • A Router is simply a Shelf Middleware component.
  • You can define a single Router for your whole application or as many as you like in a heirarchical structure.
  • When a Router passes a request to a child route it first modifies the request as follows:
    • The route's path is removed from the start of pathInfo. e.g. /banking/accounts -> /accounts
    • The route's path is appended to the scriptName. e.g. / -> /banking
    • That supports modularity in the child routes as the pathInfo only contains the path relative to that component.

Example #

See example/routing_example.dart

import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_route/shelf_route.dart' as route;

void main() {
  var publicRoute = const shelf.Stack()
      .addHandler(_echoRequest);

  var router = (route.router()
      ..addRoute(publicRoute, path: '/public')
      ..addRoute(_bankingRoutes(), path: '/banking'))
      .handler;

  var handler = const shelf.Stack()
      .addMiddleware(shelf.logRequests())
      .addHandler(router);

  io.serve(handler, 'localhost', 8080).then((server) {
    print('Serving at http://${server.address.host}:${server.port}');
  });
}

shelf.Response _echoRequest(shelf.Request request) {
  return new shelf.Response.ok('Request for "${request.pathInfo}"');
}

// supports modularity with routes. i.e. here the banking section has it's own routes
// these are relative to where the main router places them
shelf.Handler _bankingRoutes() {
  var accountsRoute = const shelf.Stack()
      .addHandler(_echoRequest);

  var transfersRoute = const shelf.Stack()
      .addHandler(_echoRequest);

  var bankingRouter = (route.router()
      ..addRoute(accountsRoute, path: '/accounts')
      ..addRoute(transfersRoute, path: '/transfers'))
      .handler;

  var bankingRoute = const shelf.Stack()
//      .addMiddleware(authenticator); // obviously they would be authenticated
      .addHandler(bankingRouter);

  return bankingRoute;
}

TODO #

  • Improve tests
  • Add support for path variables and access to their values in downstream handlers

Authors #

0
likes
0
pub points
38%
popularity

Publisher

unverified uploader

A sample command-line application

Homepage

License

unknown (LICENSE)

Dependencies

shelf

More

Packages that depend on shelf_route