'NestJS - Increase response timeout for particular http endpoint
I just started to learn about NestJS and I am wondering how could I manipulate response timeout for particular endpoints?
I could do it on a server level like:
const server = await app.listen(...);
server.setTimeout(1800000)
or on endpoint, which looks bad:
@Post('/test')
public async import(...props, @Res() res: Response): Promise<string> {
res.setTimeout(1800000)
}
But how could I do that on controller or method level? I have tried to increase timeout on endpoint using interceptors like:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, take, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
timeout(1800000),
catchError(err => {
if (err instanceof TimeoutError) {
return throwError(() => new RequestTimeoutException());
}
return throwError(() => err);
}),
);
};
};
And applying it on endpoint like:
@Post('/test')
@UseInterceptors(TimeoutInterceptor)
public async import(...props, @Res() res: Response): Promise<string> {
long running code...
}
Although interceptor is triggered so I am able to log something the timeout does not seems to work at all :/
Solution 1:[1]
Okay, if someone is curious this is what I have done:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const response = context.switchToHttp().getResponse();
response.setTimeout(600000)
return next.handle();
};
};
Solution 2:[2]
Your code hase the same complexity O(n^2) as usual selection sort, you just fill sorted items from the end rather than from start.
There are n-1 loops with run lengths n,n-1, n-2..1, so sum of arithmetic progression gives about n*(n-1)/2 comparisons and n exchanges.
Also note that the best time case of selection sort is quadratic, not linear (selection sort doesn't retrieve information to stop early)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mateusz Gebroski |
| Solution 2 | MBo |
