NestJS - request timeout
You can pass a express instance to the NextFactory.create(module, expressInstance)
so you can add the middleware to that express instance like
const expressInstance = express();express.use(timeout('4'));express.use((err, res, req, next) => req.jsonp(err)); // DON'T USE FOR PRODUCTIONconst app = NestFactory.create(AppModule, express);
It should work.
NestJS has a feature called Interceptors. Interceptors can be used for the purpose of forcing timeouts, they demonstrate it here, TimeoutInterceptor.
Suppose you have got your Interceptor in a file called timeout.interceptor.ts
:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';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); }), ); };};
After this, you have to register it, which can be done in several ways. The global registration way is shown below:
const app = await NestFactory.create(AppModule);app.useGlobalInterceptors(new TimeoutInterceptor());