File

apps/recallassess/recallassess-api/src/api/shared/system-log/interceptors/system-log-status-code.interceptor.ts

Description

Stamps status_code into system_log rows created during the request.

Why: SystemLogService writes the row early (inside service methods), before the HTTP framework finalizes the response status. This interceptor runs after the handler so we can persist the response status.

Index

Methods

Constructor

constructor(systemLogService: SystemLogService)
Parameters :
Name Type Optional
systemLogService SystemLogService No

Methods

intercept
intercept(context: ExecutionContext, next: CallHandler)
Parameters :
Name Type Optional
context ExecutionContext No
next CallHandler No
Returns : any
import { HttpException } from "@nestjs/common";
import { Injectable, Scope } from "@nestjs/common";
import type { NestInterceptor } from "@nestjs/common";
import type { ExecutionContext } from "@nestjs/common";
import type { CallHandler } from "@nestjs/common";
import { from, throwError } from "rxjs";
import { catchError, tap } from "rxjs/operators";
import { SystemLogService } from "../../services/system-log.service";

/**
 * Stamps `status_code` into system_log rows created during the request.
 *
 * Why: `SystemLogService` writes the row early (inside service methods),
 * before the HTTP framework finalizes the response status.
 * This interceptor runs after the handler so we can persist the response status.
 */
@Injectable({ scope: Scope.REQUEST })
export class SystemLogStatusCodeInterceptor implements NestInterceptor {
  constructor(private readonly systemLogService: SystemLogService) {}

  intercept(context: ExecutionContext, next: CallHandler) {
    const http = context.switchToHttp();
    const res = http.getResponse<any>();
    const start = Date.now();

    return next.handle().pipe(
      tap(() => {
        const statusCode = typeof res?.statusCode === "number" ? res.statusCode : 200;
        void this.systemLogService.applyResponseStatusToPendingLogs(statusCode, Date.now() - start);
      }),
      catchError((err) => {
        const statusCode =
          err instanceof HttpException ? err.getStatus() : typeof res?.statusCode === "number" ? res.statusCode : 500;
        void this.systemLogService.applyResponseStatusToPendingLogs(statusCode, Date.now() - start);
        return throwError(() => err);
      }),
    );
  }
}

results matching ""

    No results matching ""