|
| 1 | +import { setTimeout } from 'node:timers/promises' |
1 | 2 | import { CACHE_MAX_AGE_ONE_HOUR } from '#shared/utils/constants' |
2 | 3 |
|
3 | 4 | const GITHUB_HEADERS = { |
@@ -31,21 +32,49 @@ export default defineCachedEventHandler( |
31 | 32 | const query = `repo:${owner}/${repo} is:issue is:open` |
32 | 33 | const url = `https://api.github.com/search/issues?q=${encodeURIComponent(query)}&per_page=1` |
33 | 34 |
|
34 | | - try { |
35 | | - const data = await $fetch<GitHubSearchResponse>(url, { |
36 | | - headers: GITHUB_HEADERS, |
37 | | - }) |
38 | | - return { |
39 | | - owner, |
40 | | - repo, |
41 | | - issues: data.total_count, |
| 35 | + const maxAttempts = 3 |
| 36 | + let delayMs = 1000 |
| 37 | + |
| 38 | + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { |
| 39 | + try { |
| 40 | + const response = await $fetch.raw<GitHubSearchResponse>(url, { |
| 41 | + headers: GITHUB_HEADERS, |
| 42 | + timeout: 10000, |
| 43 | + }) |
| 44 | + |
| 45 | + if (response.status === 200) { |
| 46 | + return { |
| 47 | + owner, |
| 48 | + repo, |
| 49 | + issues: response._data?.total_count ?? 0, |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if (response.status === 202) { |
| 54 | + if (attempt === maxAttempts - 1) break |
| 55 | + await setTimeout(delayMs) |
| 56 | + delayMs = Math.min(delayMs * 2, 16_000) |
| 57 | + continue |
| 58 | + } |
| 59 | + |
| 60 | + break |
| 61 | + } catch (error: any) { |
| 62 | + if (attempt === maxAttempts - 1) { |
| 63 | + throw createError({ |
| 64 | + statusCode: error.response?.status || 500, |
| 65 | + statusMessage: |
| 66 | + error.response?._data?.message || 'Failed to fetch issue count from GitHub', |
| 67 | + }) |
| 68 | + } |
| 69 | + await setTimeout(delayMs) |
| 70 | + delayMs = Math.min(delayMs * 2, 16_000) |
42 | 71 | } |
43 | | - } catch (error: any) { |
44 | | - throw createError({ |
45 | | - statusCode: error.response?.status || 500, |
46 | | - statusMessage: error.response?._data?.message || 'Failed to fetch issue count from GitHub', |
47 | | - }) |
48 | 72 | } |
| 73 | + |
| 74 | + throw createError({ |
| 75 | + statusCode: 500, |
| 76 | + statusMessage: 'Failed to fetch issue count from GitHub after retries', |
| 77 | + }) |
49 | 78 | }, |
50 | 79 | { |
51 | 80 | maxAge: CACHE_MAX_AGE_ONE_HOUR, |
|
0 commit comments