29 lines
1.4 KiB
TypeScript
29 lines
1.4 KiB
TypeScript
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Optional } from '@nestjs/common';
|
|
import { Observable, tap } from 'rxjs';
|
|
import { ProtocolLogsService } from '../protocol-logs/protocol-logs.service';
|
|
import { publicOpenApiFailure } from './open-api.protocol';
|
|
import type { OpenApiRequestLike } from './open-api.types';
|
|
|
|
@Injectable()
|
|
export class OpenApiTraceInterceptor implements NestInterceptor {
|
|
constructor(@Optional() private readonly logs?: ProtocolLogsService) {}
|
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
const request = context.switchToHttp().getRequest<OpenApiRequestLike>();
|
|
const startedAt = Date.now();
|
|
const record = (error?: unknown) =>
|
|
this.logs?.record({
|
|
protocol: 'http',
|
|
direction: 'client_to_platform',
|
|
eventType: request.method === 'GET' ? 'query_request' : 'send_request',
|
|
status: error ? 'failed' : 'success',
|
|
requestId: request.openApiRequestId,
|
|
tenantId: request.openApiAuth?.application.tenantId,
|
|
applicationId: request.openApiAuth?.application.id,
|
|
resultCode: error ? publicOpenApiFailure(error).code : 'OK',
|
|
durationMs: Date.now() - startedAt,
|
|
detail: { method: request.method, operation: context.getHandler().name },
|
|
});
|
|
return next.handle().pipe(tap({ next: () => record(), error: (error: unknown) => record(error) }));
|
|
}
|
|
}
|