forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[repo].get.ts
More file actions
90 lines (78 loc) · 2.39 KB
/
[repo].get.ts
File metadata and controls
90 lines (78 loc) · 2.39 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { setTimeout } from 'node:timers/promises'
import { CACHE_MAX_AGE_ONE_HOUR } from '#shared/utils/constants'
const GITHUB_HEADERS = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'npmx',
'X-GitHub-Api-Version': '2022-11-28',
} as const
interface GitHubSearchResponse {
total_count: number
}
export interface GithubIssueCountResponse {
owner: string
repo: string
issues: number | null
}
export default defineCachedEventHandler(
async (event): Promise<GithubIssueCountResponse> => {
const owner = getRouterParam(event, 'owner')
const repo = getRouterParam(event, 'repo')
if (!owner || !repo) {
throw createError({
statusCode: 400,
statusMessage: 'Owner and repo are required parameters.',
})
}
const query = `repo:${owner}/${repo} is:issue is:open`
const url = `https://api.github.com/search/issues?q=${encodeURIComponent(query)}&per_page=1`
const maxAttempts = 3
let delayMs = 1000
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
try {
const response = await $fetch.raw<GitHubSearchResponse>(url, {
headers: GITHUB_HEADERS,
timeout: 10000,
})
if (response.status === 200) {
return {
owner,
repo,
issues:
typeof response._data?.total_count === 'number' ? response._data.total_count : null,
}
}
if (response.status === 202) {
if (attempt === maxAttempts - 1) break
await setTimeout(delayMs)
delayMs = Math.min(delayMs * 2, 16_000)
continue
}
break
} catch (error: any) {
if (attempt === maxAttempts - 1) {
throw createError({
statusCode: error.response?.status || 500,
statusMessage:
error.response?._data?.message || 'Failed to fetch issue count from GitHub',
})
}
await setTimeout(delayMs)
delayMs = Math.min(delayMs * 2, 16_000)
}
}
throw createError({
statusCode: 500,
statusMessage: 'Failed to fetch issue count from GitHub after retries',
})
},
{
maxAge: CACHE_MAX_AGE_ONE_HOUR,
swr: true,
name: 'github-issue-count',
getKey: event => {
const owner = getRouterParam(event, 'owner')
const repo = getRouterParam(event, 'repo')
return `${owner}/${repo}`
},
},
)