toMiddleware method

  1. @override
Middleware toMiddleware()
override

Builds the shelf middleware this value configures.

Implementation

@override
Middleware toMiddleware() {
  return (Handler inner) {
    return (Request request) async {
      final stopwatch = Stopwatch()..start();

      // The router fills this on the way through. A layer wraps the matcher,
      // so it cannot read the matched route off its own request.
      final matched = MatchedRouteSlot();
      final logged = request.change(
        context: {matchedRouteSlotKey: matched},
      );

      final Response response;
      try {
        response = await inner(logged);
      } on HijackException {
        // An upgrade succeeds by throwing, so without this a WebSocket
        // connection never reaches the log at all — you cannot see who
        // connected, when, or from where. 101 is what went on the wire.
        stopwatch.stop();
        onRecord(
          AccessRecord(
            method: request.method,
            path: '/${request.url.path}',
            status: 101,
            duration: stopwatch.elapsed,
            requestId: requestIdOf(request),
            matchedRoute: matched.route,
          ),
        );
        rethrow;
      }
      stopwatch.stop();

      onRecord(
        AccessRecord(
          method: request.method,
          path: '/${request.url.path}',
          status: response.statusCode,
          duration: stopwatch.elapsed,
          requestId: requestIdOf(request),
          matchedRoute: matched.route,
        ),
      );
      return response;
    };
  };
}