| 5 | |
| 6 | /** Run a single GraphQL query. Throws if the response carries `errors`. */ |
| 7 | export async function graphql<T>( |
| 8 | token: string, |
| 9 | query: string, |
| 10 | variables: Record<string, unknown>, |
| 11 | ): Promise<T> { |
| 12 | const res = await fetch(`${GITHUB_API}/graphql`, { |
| 13 | method: "POST", |
| 14 | headers: { |
| 15 | Authorization: `token ${token}`, |
| 16 | "User-Agent": USER_AGENT, |
| 17 | "Content-Type": "application/json", |
| 18 | }, |
| 19 | body: JSON.stringify({ query, variables }), |
| 20 | }); |
| 21 | if (!res.ok) { |
| 22 | throw new Error(`GitHub GraphQL -> ${res.status}: ${await res.text()}`); |
| 23 | } |
| 24 | const body = (await res.json()) as { data?: T; errors?: unknown }; |
| 25 | if (body.errors) { |
| 26 | throw new Error( |
| 27 | `GitHub GraphQL errors: ${JSON.stringify(body.errors)}`, |
| 28 | ); |
| 29 | } |
| 30 | if (!body.data) { |
| 31 | throw new Error("GitHub GraphQL returned no data"); |
| 32 | } |
| 33 | return body.data; |
| 34 | } |