-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.ts
More file actions
186 lines (170 loc) · 6.12 KB
/
github.ts
File metadata and controls
186 lines (170 loc) · 6.12 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from '@tanstack/react-query'
interface GitHubFetcherOptions {
baseURL?: string
timeout?: number
userAgent?: string
authToken?: string
}
interface GitHubResponse<T> {
data: T
headers: Record<string, string>
status: number
}
// Rate limit state (module-level, not per-request)
let rateLimitRemaining = 60
let rateLimitReset = 0
function updateRateLimits(headers: Record<string, string>) {
const remaining = headers['x-ratelimit-remaining']
const reset = headers['x-ratelimit-reset']
if (remaining) rateLimitRemaining = parseInt(remaining, 10)
if (reset) rateLimitReset = parseInt(reset, 10)
}
export function getRateLimitInfo() {
return {
remaining: rateLimitRemaining,
reset: rateLimitReset,
resetTime: new Date(rateLimitReset * 1000)
}
}
function getHeaders(options?: GitHubFetcherOptions) {
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': options?.userAgent || 'InfinityBotList'
}
const token = process.env.GITHUB_TOKEN
if (token) headers['Authorization'] = `Bearer ${token}`
return headers
}
async function githubFetch<T>(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
endpoint: string,
data?: any,
options?: GitHubFetcherOptions & { fetchOptions?: RequestInit }
): Promise<GitHubResponse<T>> {
const baseURL = options?.baseURL || 'https://api.github.com'
const url = endpoint.startsWith('http') ? endpoint : `${baseURL}${endpoint}`
const headers = {
...getHeaders(options),
...(options?.fetchOptions?.headers || {})
}
const fetchOptions: RequestInit = {
method,
headers,
...options?.fetchOptions
}
if (data && method !== 'GET') {
fetchOptions.body = JSON.stringify(data)
// Ensure headers is a Record<string, string>
if (typeof headers === 'object' && headers !== null && !Array.isArray(headers)) {
;(headers as Record<string, string>)['Content-Type'] = 'application/json'
}
}
const res = await fetch(url, fetchOptions)
const resHeaders: Record<string, string> = {}
res.headers.forEach((v, k) => {
resHeaders[k] = v
})
updateRateLimits(resHeaders)
const contentType = res.headers.get('content-type') || ''
let responseData: any = undefined
if (contentType.includes('application/json')) {
responseData = await res.json()
} else {
responseData = await res.text()
}
if (!res.ok) {
const status = res.status
const message = responseData?.message || res.statusText
switch (status) {
case 401:
case 403:
throw new Error(
`GitHub API Authentication Error: ${message}. Please check your GitHub token configuration.`
)
case 404:
throw new Error(`GitHub API Resource Not Found: ${message}`)
case 429:
const resetTime = res.headers.get('x-ratelimit-reset')
const retryAfter = resetTime ? new Date(parseInt(resetTime) * 1000) : 'unknown'
throw new Error(`GitHub API Rate Limit Exceeded. Please try again after ${retryAfter}`)
default:
throw new Error(`GitHub API Error (${status}): ${message}`)
}
}
return {
data: responseData,
headers: resHeaders,
status: res.status
}
}
// --- React Query hooks ---
export function useGitHubQuery<T = unknown, E = unknown>(
key: QueryKey,
endpoint: string,
options?: UseQueryOptions<GitHubResponse<T>, E> & { fetcherOptions?: GitHubFetcherOptions }
) {
return useQuery<GitHubResponse<T>, E>({
queryKey: key,
queryFn: () => githubFetch<T>('GET', endpoint, undefined, options?.fetcherOptions),
...options
})
}
export function useGitHubMutation<T = unknown, V = any, E = unknown>(
method: 'POST' | 'PUT' | 'DELETE',
endpoint: string,
options?: UseMutationOptions<GitHubResponse<T>, E, V> & { fetcherOptions?: GitHubFetcherOptions }
) {
return useMutation<GitHubResponse<T>, E, V>({
mutationFn: (variables: V) => githubFetch<T>(method, endpoint, variables, options?.fetcherOptions),
...options
})
}
// Convenience hooks
export function useGitHubPost<T = unknown, V = any, E = unknown>(
endpoint: string,
options?: UseMutationOptions<GitHubResponse<T>, E, V> & { fetcherOptions?: GitHubFetcherOptions }
) {
return useGitHubMutation<T, V, E>('POST', endpoint, options)
}
export function useGitHubPut<T = unknown, V = any, E = unknown>(
endpoint: string,
options?: UseMutationOptions<GitHubResponse<T>, E, V> & { fetcherOptions?: GitHubFetcherOptions }
) {
return useGitHubMutation<T, V, E>('PUT', endpoint, options)
}
export function useGitHubDelete<T = unknown, V = any, E = unknown>(
endpoint: string,
options?: UseMutationOptions<GitHubResponse<T>, E, V> & { fetcherOptions?: GitHubFetcherOptions }
) {
return useGitHubMutation<T, V, E>('DELETE', endpoint, options)
}
// --- Class-based API ---
class GitHubFetcher {
async get<T = unknown>(endpoint: string, options?: GitHubFetcherOptions & { fetchOptions?: RequestInit }) {
return githubFetch<T>('GET', endpoint, undefined, options)
}
async post<T = unknown, V = any>(
endpoint: string,
data?: V,
options?: GitHubFetcherOptions & { fetchOptions?: RequestInit }
) {
return githubFetch<T>('POST', endpoint, data, options)
}
async put<T = unknown, V = any>(
endpoint: string,
data?: V,
options?: GitHubFetcherOptions & { fetchOptions?: RequestInit }
) {
return githubFetch<T>('PUT', endpoint, data, options)
}
async delete<T = unknown, V = any>(
endpoint: string,
data?: V,
options?: GitHubFetcherOptions & { fetchOptions?: RequestInit }
) {
return githubFetch<T>('DELETE', endpoint, data, options)
}
}
const githubFetcher = new GitHubFetcher()
export { GitHubFetcher, githubFetcher }
export default githubFetcher