|
1 | | -import { Injectable } from '@nestjs/common'; |
| 1 | +import { Injectable, HttpException, HttpStatus } from '@nestjs/common'; |
2 | 2 | import { ConfigService } from '@nestjs/config'; |
3 | 3 |
|
4 | 4 | @Injectable() |
5 | 5 | export class AppService { |
| 6 | + private readonly maxRetries = 3; |
| 7 | + private readonly retryDelayMs = 1000; |
| 8 | + private readonly timeoutMs = 30000; |
| 9 | + |
6 | 10 | constructor(private configService: ConfigService) {} |
7 | 11 |
|
8 | 12 | getHello(): string { |
@@ -38,8 +42,49 @@ export class AppService { |
38 | 42 | 'TODOS_API_BASE_URL', |
39 | 43 | 'https://jsonplaceholder.typicode.com', |
40 | 44 | ); |
41 | | - const response = await fetch(`${baseUrl}/todos/${id}`); |
42 | | - return await response.json(); |
| 45 | + |
| 46 | + for (let attempt = 0; attempt < this.maxRetries; attempt++) { |
| 47 | + try { |
| 48 | + const controller = new AbortController(); |
| 49 | + const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs); |
| 50 | + |
| 51 | + const response = await fetch(`${baseUrl}/todos/${id}`, { |
| 52 | + signal: controller.signal, |
| 53 | + }); |
| 54 | + |
| 55 | + clearTimeout(timeoutId); |
| 56 | + |
| 57 | + if (!response.ok) { |
| 58 | + if (response.status === 404) { |
| 59 | + throw new HttpException('Todo not found', HttpStatus.NOT_FOUND); |
| 60 | + } |
| 61 | + throw new Error(`HTTP error! status: ${response.status}`); |
| 62 | + } |
| 63 | + |
| 64 | + const todo = await response.json(); |
| 65 | + |
| 66 | + if (!todo) { |
| 67 | + throw new HttpException('Todo not found', HttpStatus.NOT_FOUND); |
| 68 | + } |
| 69 | + |
| 70 | + return todo; |
| 71 | + } catch (error) { |
| 72 | + if (error instanceof HttpException && error.getStatus() === HttpStatus.NOT_FOUND) { |
| 73 | + throw error; |
| 74 | + } |
| 75 | + |
| 76 | + if (attempt === this.maxRetries - 1) { |
| 77 | + throw new HttpException( |
| 78 | + `External API is unavailable after ${this.maxRetries} attempts: ${error.message}`, |
| 79 | + HttpStatus.SERVICE_UNAVAILABLE, |
| 80 | + ); |
| 81 | + } |
| 82 | + |
| 83 | + await new Promise(resolve => setTimeout(resolve, this.retryDelayMs)); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + throw new HttpException('Unexpected error', HttpStatus.INTERNAL_SERVER_ERROR); |
43 | 88 | } |
44 | 89 |
|
45 | 90 | getTodosPageHtml(): string { |
|
0 commit comments