Routing Requests

This is an action in the default HTTP sequence. Its responsibility is to find aroute that can handle a given http request. By default, the FindRoute actionuses the RoutingTable from @loopback/rest to match requests againstregistered routes including controller methods using request.method andrequest.path. For example:

  • GET /orders => OrderController.getOrders (@get('/orders'))
  • GET /orders/123 => OrderController.getOrderById (@get('/orders/{id}'))
  • GET /orders/count => OrderController.getOrderCount (@get('/orders/count'))
  • POST /orders => OrderController.createOrder (@post('/orders'))

Customize the FindRoute action

The FindRoute action is bound to SequenceActions.FIND_ROUTE(‘rest.sequence.actions.findRoute’) and injected into the default sequence.

To create your own FindRoute action, bind your implementation as follows:

  1. const yourFindRoute: FindRoute = ...;
  2. app.bind(SequenceActions.FIND_ROUTE).to(yourFindRoute);

Customize the REST Router

Instead of rewriting FindRoute action completely, LoopBack 4 also allows youto simply replace the RestRouter implementation.

The @loopback/rest module ships two built-in routers:

  • TrieRouter: it keeps routes as a trie tree and uses traversal to matchrequest to routes based on the hierarchy of the path
  • RegExpRouter: it keeps routes as an array and uses path-to-regexp to matchrequest to routes based on the path patternFor both routers, routes without variables are optimized in a map so that anyrequests matching to a fixed path can be resolved quickly.

By default, @loopback/rest uses TrieRouter as it performs better thanRegExpRouter. There is a simple benchmarking for RegExpRouter andTrieRouter athttps://githhub.com/strongloop/loopback-next/benchmark/src/rest-routing/routing-table.ts.

To change the router for REST routing, we can bind the router class as follows:

  1. import {RestBindings, RegExpRouter} from '@loopback/rest';
  2. app.bind(RestBindings.ROUTER).toClass(RegExpRouter);

It’s also possible to have your own implementation of RestRouter interfacebelow:

  1. /**
  2. * Interface for router implementation
  3. */
  4. export interface RestRouter {
  5. /**
  6. * Add a route to the router
  7. * @param route - A route entry
  8. */
  9. add(route: RouteEntry): boolean;
  10. /**
  11. * Find a matching route for the given http request
  12. * @param request - Http request
  13. * @returns The resolved route, if not found, `undefined` is returned
  14. */
  15. find(request: Request): ResolvedRoute | undefined;
  16. /**
  17. * List all routes
  18. */
  19. list(): RouteEntry[];
  20. }

See examples at: