Skip to content

Commit 981a2f2

Browse files
Merge pull request #184 from akargi/feat/Issue173
Feat: Global TimeoutInterceptor Implementation
2 parents ab7fc27 + e9744d5 commit 981a2f2

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

src/main.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)