Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

github.ts

82 lines2.5 KB

1/**
2 * Thin GitHub API client. Token and fetch are injected so tests never touch
3 * the network and callers control auth.
4 */
5​
6export interface GitHubClient {
7 graphql: <T>(query: string, variables: Record<string, unknown>) => Promise<T>
8 rest: (
9 method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
10 path: string,
11 body?: unknown,
12 ) => Promise<unknown>
14​
15export interface GitHubClientOptions {
16 token: string
17 fetchImpl?: typeof fetch
18 baseUrl?: string
19 /** Per-request deadline; a stalled connection aborts instead of hanging the job. */
20 timeoutMs?: number
22​
23export function createGitHubClient(options: GitHubClientOptions): GitHubClient {
24 const fetchImpl = options.fetchImpl ?? fetch
25 const baseUrl = options.baseUrl ?? 'https://api.github.com'
26 const timeoutMs = options.timeoutMs ?? 30_000
27 const headers = {
28 authorization: `Bearer ${options.token}`,
29 accept: 'application/vnd.github+json',
30 'content-type': 'application/json',
31 'user-agent': 'tanstack-ai-maintainer-toolset',
32 'x-github-api-version': '2022-11-28',
33 }
34​
35 return {
36 async graphql<T>(
37 query: string,
38 variables: Record<string, unknown>,
39 ): Promise<T> {
40 const response = await fetchImpl(`${baseUrl}/graphql`, {
41 method: 'POST',
42 headers,
43 body: JSON.stringify({ query, variables }),
44 signal: AbortSignal.timeout(timeoutMs),
45 })
46 const payload: unknown = await response.json()
47 if (!response.ok) {
48 throw new Error(
49 `GitHub GraphQL HTTP ${response.status}: ${JSON.stringify(payload).slice(0, 500)}`,
50 )
51 }
52 if (
53 typeof payload === 'object' &&
54 payload !== null &&
55 'errors' in payload &&
56 Array.isArray(payload.errors) &&
57 (payload as { errors: Array<unknown> }).errors.length > 0
58 ) {
59 throw new Error(
60 `GitHub GraphQL errors: ${JSON.stringify(payload.errors).slice(0, 800)}`,
61 )
62 }
63 return (payload as { data: T }).data
64 },
65​
66 async rest(method, path, body): Promise<unknown> {
67 const response = await fetchImpl(`${baseUrl}${path}`, {
68 method,
69 headers,
70 body: body === undefined ? undefined : JSON.stringify(body),
71 signal: AbortSignal.timeout(timeoutMs),
72 })
73 const text = await response.text()
74 if (!response.ok) {
75 throw new Error(
76 `GitHub REST ${method} ${path} → HTTP ${response.status}: ${text.slice(0, 500)}`,
77 )
78 }
79 return text.length > 0 ? JSON.parse(text) : null
80 },
81 }