peekApiMiddleware function

Middleware peekApiMiddleware(
  1. PeekApiClient? client, {
  2. PeekApiOptions? options,
})

Creates a Shelf Middleware that tracks API requests with PeekAPI.

Usage:

final handler = const Pipeline()
    .addMiddleware(peekApiMiddleware(client))
    .addHandler(router);

Implementation

Middleware peekApiMiddleware(
  PeekApiClient? client, {
  PeekApiOptions? options,
}) {
  return (Handler innerHandler) {
    return (Request request) async {
      // Null client → passthrough
      if (client == null) return innerHandler(request);

      final stopwatch = Stopwatch()..start();
      Response response;

      try {
        response = await innerHandler(request);
      } catch (e) {
        stopwatch.stop();
        // Track the error but rethrow
        try {
          _trackRequest(
            client,
            options,
            request,
            500,
            stopwatch.elapsedMicroseconds / 1000.0,
            0,
          );
        } catch (_) {
          // Never break the request
        }
        rethrow;
      }

      stopwatch.stop();

      try {
        final responseSize = response.contentLength ?? 0;
        _trackRequest(
          client,
          options,
          request,
          response.statusCode,
          stopwatch.elapsedMicroseconds / 1000.0,
          responseSize,
        );
      } catch (_) {
        // Never break the response
      }

      return response;
    };
  };
}