feat: 完善服务监控与下游重投
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import type { Observable } from 'rxjs';
|
||||
import { finalize } from 'rxjs/operators';
|
||||
import { MetricsService } from './metrics.service';
|
||||
|
||||
type RequestLike = { method?: string; baseUrl?: string; route?: { path?: string } };
|
||||
type ResponseLike = { statusCode?: number };
|
||||
|
||||
@Injectable()
|
||||
export class MetricsInterceptor implements NestInterceptor {
|
||||
constructor(private readonly metrics: MetricsService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
if (context.getType() !== 'http') return next.handle();
|
||||
const http = context.switchToHttp();
|
||||
const request = http.getRequest<RequestLike>();
|
||||
const response = http.getResponse<ResponseLike>();
|
||||
const startedAt = this.metrics.beginRequest();
|
||||
return next.handle().pipe(finalize(() => {
|
||||
const route = `${request.baseUrl ?? ''}${request.route?.path ?? '/unmatched'}`;
|
||||
this.metrics.finishRequest(startedAt, request.method ?? 'UNKNOWN', route, response.statusCode ?? 500);
|
||||
}));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user