Hi!
I'm using the Timeout Interceptor from the documentation to manage timeouts on my API.
https://docs.nestjs.com/interceptors
But if I simulate an infinite loop on my controller, I receive the timeout response but the loop continues its execution. This can cause a memory leak on the service. How do you manage your timeouts to avoid this?
timeout.interceptor.ts
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
timeout(5000),
catchError(err => {
if (err instanceof TimeoutError) {
return throwError(() => new RequestTimeoutException());
}
return throwError(() => err);
}),
);
};
};```
app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
async getHello(): Promise<string> {
let second = 0;
while (1 + 1 == 2) {
console.log('Waiting...' + second++);
await this.sleep(1000);
}
return this.appService.getHello();
}
async sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}```
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).