-
Notifications
You must be signed in to change notification settings - Fork 100
/
github-api.ts
74 lines (63 loc) · 1.74 KB
/
github-api.ts
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
const path = require("path");
import ConfigurationError from "./configuration-error";
import fetch from "./fetch";
export interface GitHubUserResponse {
login: string;
name: string;
html_url: string;
}
export interface GitHubIssueResponse {
number: number;
title: string;
pull_request?: {
html_url: string;
};
labels: Array<{
name: string;
}>;
user: {
login: string;
html_url: string;
};
}
export interface Options {
repo: string;
rootPath: string;
cacheDir?: string;
}
export default class GithubAPI {
private cacheDir: string | undefined;
private auth: string;
constructor(config: Options) {
this.cacheDir = config.cacheDir && path.join(config.rootPath, config.cacheDir, "github");
this.auth = this.getAuthToken();
if (!this.auth) {
throw new ConfigurationError("Must provide GITHUB_AUTH");
}
}
public getBaseIssueUrl(repo: string): string {
return `https://github.com/${repo}/issues/`;
}
public async getIssueData(repo: string, issue: string): Promise<GitHubIssueResponse> {
return this._fetch(`https://api.github.com/repos/${repo}/issues/${issue}`);
}
public async getUserData(login: string): Promise<GitHubUserResponse> {
return this._fetch(`https://api.github.com/users/${login}`);
}
private async _fetch(url: string): Promise<any> {
const res = await fetch(url, {
cachePath: this.cacheDir,
headers: {
Authorization: `token ${this.auth}`,
},
});
const parsedResponse = await res.json();
if (res.ok) {
return parsedResponse;
}
throw new ConfigurationError(`Fetch error: ${res.statusText}.\n${JSON.stringify(parsedResponse)}`);
}
private getAuthToken(): string {
return process.env.GITHUB_AUTH || "";
}
}