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 62 63 64 65 66 67 68 69 70 71 | import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { Reflector } from '@nestjs/core'; @Injectable() export class ApiAuditInterceptor implements NestInterceptor { private readonly logger = new Logger('API_AUDIT'); constructor(private readonly reflector: Reflector) {} intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const request = context.switchToHttp().getRequest(); const response = context.switchToHttp().getResponse(); const startTime = Date.now(); const requestId: string = request['requestId'] || 'unknown'; const correlationId: string = request['correlationId'] || 'unknown'; const tenantId: string = request.user?.tenantId || 'anonymous'; const userId: string = request.user?.userId || 'anonymous'; const method = request.method; const url = request.url; return next.handle().pipe( tap({ next: () => { const duration = Date.now() - startTime; const statusCode = response.statusCode; this.logger.log( JSON.stringify({ type: 'api_request', requestId, correlationId, tenantId, userId, method, url, statusCode, durationMs: duration, timestamp: new Date().toISOString(), }), ); }, error: (err) => { const duration = Date.now() - startTime; this.logger.error( JSON.stringify({ type: 'api_error', requestId, correlationId, tenantId, userId, method, url, errorCode: err.code || 'UNKNOWN', durationMs: duration, timestamp: new Date().toISOString(), }), ); }, }), ); } } |