-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathgithub-api.mjs
More file actions
61 lines (56 loc) · 1.8 KB
/
Copy pathgithub-api.mjs
File metadata and controls
61 lines (56 loc) · 1.8 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
export function getGitHubRuntime(environment = process.env) {
const token = environment.GH_TOKEN;
const repository = environment.REPOSITORY;
const pullRequestNumber = Number(environment.PR_NUMBER);
if (!token) {
throw new Error('GH_TOKEN is required');
}
if (!/^[^/]+\/[^/]+$/.test(repository ?? '')) {
throw new Error('REPOSITORY must use the owner/name format');
}
if (!Number.isInteger(pullRequestNumber) || pullRequestNumber <= 0) {
throw new Error('PR_NUMBER must be a positive integer');
}
return {
token,
repository,
pullRequestNumber,
apiBase: environment.GITHUB_API_URL || 'https://api.github.com',
};
}
export function createGitHubClient({token, apiBase, fetchImplementation = fetch}) {
async function request(path, options = {}) {
const response = await fetchImplementation(`${apiBase}${path}`, {
...options,
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
...options.headers,
},
});
const text = await response.text();
const data = text ? JSON.parse(text) : null;
if (!response.ok) {
const details = data?.errors ? ` ${JSON.stringify(data.errors)}` : '';
const error = new Error(
`GitHub API ${response.status}: ${data?.message ?? text}${details}`
);
error.status = response.status;
throw error;
}
return data;
}
async function paginate(path) {
const items = [];
for (let page = 1; ; page += 1) {
const separator = path.includes('?') ? '&' : '?';
const result = await request(`${path}${separator}per_page=100&page=${page}`);
items.push(...result);
if (result.length < 100) {
return items;
}
}
}
return {request, paginate};
}