handleRequest method

Future<HttpResponse> handleRequest(
  1. HttpRequest httpRequest
)
inherited

Implementation

Future<HttpResponse> handleRequest(HttpRequest httpRequest) async {
  final watch = Stopwatch();
  watch.start();
  return _inst.trace(
    'HTTP ${httpRequest.method.name.toUpperCase()}',
    SpanType.server,
    {
      'http.request.route': httpRequest.path,
      'http.request.method': httpRequest.method.name.toUpperCase(),
    },
    () async {
      try {
        final response = await runZoned(
          () async {
            try {
              final handler = _findRequestHandler(httpRequest.path);
              final path = httpRequest.path.startsWith(basePath)
                  ? httpRequest.path.substring(basePath.length)
                  : '';

              final route = (handler is ApiEndpoint)
                  ? handler.routePattern.decode(path)
                  : Route(RoutePattern.any, path, {}, path);

              //TODO cookies

              final request = ApiRequest(
                httpRequest.method,
                route,
                httpRequest.headers,
                httpRequest.queryParams,
                httpRequest.bodyData,
                null,
              );

              final response = await (middleware?.call(handler) ?? handler)
                  .handleRequest(request);

              return response.toHttpResponse(httpRequest.requestUri);
            } on ApiRequestException catch (e) {
              // Exceptions should have been handled by ApiEndpoint, this is just
              // to make sure
              return e.toResponse().toHttpResponse(httpRequest.requestUri);
            } catch (e, stack) {
              // Exceptions should have been handled by ApiEndpoint, this is just
              // to make sure
              if (resolve<ConfigService>().environment == Environment.dev) {
                return DebugResponse(e, stack, 500)
                    .toHttpResponse(httpRequest.requestUri);
              } else {
                return ApiRequestException.internalError(
                        'Internal Server Error')
                    .toResponse()
                    .toHttpResponse(httpRequest.requestUri);
              }
            }
          },
          zoneValues: {
            #apiRequestId: _generateRequestId(),
          },
        );

        final statusCodeLabel = switch (response.statusCode) {
          int i when i >= 100 && i < 700 =>
            '${(response.statusCode / 100).floor()}xx',
          _ => 'other',
        };
        _metricRequestsTotal?.inc({'status_code': statusCodeLabel});
        return response;
      } finally {
        watch.stop();
        _metricRequestDuration?.observeDuration(watch.elapsed);
      }
    },
  );
}