-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathrequest.cpu.time.interceptor.ts
More file actions
56 lines (46 loc) · 1.76 KB
/
request.cpu.time.interceptor.ts
File metadata and controls
56 lines (46 loc) · 1.76 KB
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
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { Observable, throwError } from "rxjs";
import { catchError, tap } from 'rxjs/operators';
import { MetricsService } from '../metrics';
import { CpuProfiler } from "../profilers/cpu.profiler";
@Injectable()
export class RequestCpuTimeInterceptor implements NestInterceptor {
constructor(
private readonly metricsService: MetricsService,
private readonly onRequest?: (apiFunction: string, durationMs: number, context: ExecutionContext) => void,
) { }
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const contextType: string = context.getType();
if (!["http", "https"].includes(contextType)) {
return next.handle();
}
const apiFunction = context.getClass().name + '.' + context.getHandler().name;
const request = context.switchToHttp().getRequest();
const profiler = new CpuProfiler();
return next
.handle()
.pipe(
tap(() => {
const duration = profiler.stop();
this.metricsService.setApiCpuTime(apiFunction, duration);
if (this.onRequest) {
this.onRequest(apiFunction, duration, context);
}
if (!request.res.headersSent) {
request.res.set('X-Request-Cpu-Time', duration);
}
}),
catchError(err => {
const duration = profiler.stop();
this.metricsService.setApiCpuTime(apiFunction, duration);
if (this.onRequest) {
this.onRequest(apiFunction, duration, context);
}
if (!request.res.headersSent) {
request.res.set('X-Request-Cpu-Time', duration);
}
return throwError(() => err);
})
);
}
}