File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed
Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ import {
2+ Injectable ,
3+ NestInterceptor ,
4+ ExecutionContext ,
5+ CallHandler ,
6+ BadGatewayException ,
7+ } from '@nestjs/common' ;
8+ import { Observable , TimeoutError } from 'rxjs' ;
9+ import { timeout , catchError } from 'rxjs/operators' ;
10+
11+ export const DEFAULT_TIMEOUT = parseInt ( process . env . REQUEST_TIMEOUT || '10000' , 10 ) ; // ms
12+
13+ export function Timeout ( ms ?: number ) : MethodDecorator {
14+ return ( target , propertyKey , descriptor ) => {
15+ Reflect . defineMetadata ( 'timeout' , ms , descriptor . value ! ) ;
16+ } ;
17+ }
18+
19+ @Injectable ( )
20+ export class TimeoutInterceptor implements NestInterceptor {
21+ intercept ( context : ExecutionContext , next : CallHandler ) : Observable < any > {
22+ const handler = context . getHandler ( ) ;
23+ const customTimeout = Reflect . getMetadata ( 'timeout' , handler ) ;
24+ const timeoutValue = customTimeout || DEFAULT_TIMEOUT ;
25+ return next . handle ( ) . pipe (
26+ timeout ( timeoutValue ) ,
27+ catchError ( err => {
28+ if ( err instanceof TimeoutError ) {
29+ throw new BadGatewayException ( {
30+ statusCode : 504 ,
31+ message : 'Request timed out' ,
32+ error : 'Timeout' ,
33+ timestamp : new Date ( ) . toISOString ( ) ,
34+ } ) ;
35+ }
36+ throw err ;
37+ } )
38+ ) ;
39+ }
40+ }
Original file line number Diff line number Diff line change @@ -15,6 +15,10 @@ async function bootstrap() {
1515 // ─── Global Response Transform Interceptor ───────────────────────────────
1616 app . useGlobalInterceptors ( new ResponseTransformInterceptor ( ) ) ;
1717
18+ // ─── Global Timeout Interceptor ─────────────────────────────────────────
19+ const { TimeoutInterceptor } = await import ( './common/interceptors/timeout.interceptor' ) ;
20+ app . useGlobalInterceptors ( new TimeoutInterceptor ( ) ) ;
21+
1822 // ─── CORS ─────────────────────────────────────────────────────────────────
1923 app . enableCors ( ) ;
2024
You can’t perform that action at this time.
0 commit comments