-
-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathgithub.ts
More file actions
56 lines (47 loc) · 1.36 KB
/
github.ts
File metadata and controls
56 lines (47 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { setTimeout } from 'node:timers/promises'
export interface GitHubFetchOptions extends NonNullable<Parameters<typeof $fetch.raw>[1]> {
maxAttempts?: number
}
export async function fetchGitHubWithRetries<T>(
url: string,
options: GitHubFetchOptions = {},
): Promise<T | null> {
const { maxAttempts = 3, ...fetchOptions } = options
let delayMs = 1000
const defaultHeaders = {
'Accept': 'application/vnd.github+json',
'User-Agent': 'npmx',
'X-GitHub-Api-Version': '2026-03-10',
}
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
try {
const response = await $fetch.raw(url, {
...fetchOptions,
headers: {
...defaultHeaders,
...fetchOptions.headers,
},
})
if (response.status === 200) {
return (response._data as T) ?? null
}
if (response.status === 204) {
return null
}
if (response.status === 202) {
if (attempt === maxAttempts - 1) break
await setTimeout(delayMs)
delayMs = Math.min(delayMs * 2, 16_000)
continue
}
break
} catch (error: unknown) {
if (attempt === maxAttempts - 1) {
throw error
}
await setTimeout(delayMs)
delayMs = Math.min(delayMs * 2, 16_000)
}
}
throw new Error(`Failed to fetch from GitHub after ${maxAttempts} attempts`)
}