All files / libs/observability/src/metrics http-metrics.interceptor.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 6/6
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 6217x               17x 17x   17x               17x     5x       5x 1x     4x 4x   4x 4x 4x                       4x   2x           2x 2x          
import {
  CallHandler,
  ExecutionContext,
  HttpException,
  Inject,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import type { Histogram } from 'prom-client';
import { HTTP_DURATION_HISTOGRAM } from './metrics.tokens';
 
interface RequestLike {
  method: string;
  route?: { path?: string };
}
 
@Injectable()
export class HttpMetricsInterceptor implements NestInterceptor {
  constructor(
    @Inject(HTTP_DURATION_HISTOGRAM)
    private readonly histogram: Histogram<'method' | 'route' | 'status_code'>,
  ) {}
 
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    if (context.getType() !== 'http') {
      return next.handle();
    }
 
    const startedAt = process.hrtime.bigint();
    const request = context.switchToHttp().getRequest<RequestLike>();
 
    const record = (statusCode: number): void => {
      const seconds = Number(process.hrtime.bigint() - startedAt) / 1e9;
      this.histogram.observe(
        {
          method: request.method,
          // The route TEMPLATE (/work-orders/:id), never the raw URL: one
          // label value per endpoint keeps metric cardinality bounded.
          route: request.route?.path ?? 'unmatched',
          status_code: String(statusCode),
        },
        seconds,
      );
    };
 
    return next.handle().pipe(
      tap(() =>
        record(
          context.switchToHttp().getResponse<{ statusCode: number }>()
            .statusCode,
        ),
      ),
      catchError((error: unknown) => {
        record(error instanceof HttpException ? error.getStatus() : 500);
        return throwError(() => error);
      }),
    );
  }
}