Skip to content

Commit 85778ac

Browse files
committed
retry on 202
1 parent f0f4fd5 commit 85778ac

File tree

1 file changed

+31
-25
lines changed

1 file changed

+31
-25
lines changed

server/api/github/contributors-evolution/[owner]/[repo].get.ts

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import type { CachedFetchFunction, CachedFetchResult } from '#shared/utils/fetch-cache-config'
21
import { CACHE_MAX_AGE_ONE_DAY } from '#shared/utils/constants'
32

43
type GitHubContributorWeek = {
@@ -25,33 +24,40 @@ export default defineCachedEventHandler(
2524
})
2625
}
2726

28-
let cachedFetch: CachedFetchFunction
29-
if (event.context.cachedFetch) {
30-
cachedFetch = event.context.cachedFetch
31-
} else {
32-
cachedFetch = async <T = unknown>(
33-
url: string,
34-
options: Parameters<typeof $fetch>[1] = {},
35-
_ttl?: number,
36-
): Promise<CachedFetchResult<T>> => {
37-
const data = (await $fetch<T>(url, options)) as T
38-
return { data, isStale: false, cachedAt: null }
39-
}
27+
const url = `https://api.github.com/repos/${owner}/${repo}/stats/contributors`
28+
const headers = {
29+
'User-Agent': 'npmx',
30+
'Accept': 'application/vnd.github+json',
4031
}
4132

33+
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
34+
const maxAttempts = 6
35+
let delayMs = 1000
36+
4237
try {
43-
const { data } = await cachedFetch<GitHubContributorStats[]>(
44-
`https://api.github.com/repos/${owner}/${repo}/stats/contributors`,
45-
{
46-
headers: {
47-
'User-Agent': 'npmx',
48-
'Accept': 'application/vnd.github+json',
49-
},
50-
},
51-
CACHE_MAX_AGE_ONE_DAY,
52-
)
53-
54-
return Array.isArray(data) ? data : []
38+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
39+
const response = await $fetch.raw<GitHubContributorStats[]>(url, { headers })
40+
const status = response.status
41+
42+
if (status === 200) {
43+
return Array.isArray(response._data) ? response._data : []
44+
}
45+
46+
if (status === 204) {
47+
return []
48+
}
49+
50+
if (status === 202) {
51+
if (attempt === maxAttempts - 1) return []
52+
await sleep(delayMs)
53+
delayMs = Math.min(delayMs * 2, 16_000)
54+
continue
55+
}
56+
57+
return []
58+
}
59+
60+
return []
5561
} catch {
5662
return []
5763
}

0 commit comments

Comments
 (0)