This repository was archived by the owner on Jul 5, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGitHub.js
More file actions
83 lines (73 loc) · 1.86 KB
/
GitHub.js
File metadata and controls
83 lines (73 loc) · 1.86 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
const ENDPOINT = 'https://api.github.com';
function getUrl(path = [], params = {}) {
path = `/${path.join('/')}`;
const url = new URL(path, ENDPOINT);
Object.keys(params).forEach(param => {
url.searchParams.set(param, params[param]);
});
return url;
}
async function get(url) {
try {
const resp = await fetch(url, {
mode: 'cors',
method: 'GET'
});
const parsed = await(parse(resp));
if (parsed.hasOwnProperty('encoding') && parsed.encoding === 'base64') {
parsed.content = atob(parsed.content);
}
return parsed;
} catch (e) {
console.error(e);
}
}
async function parse(resp) {
if (resp.ok) {
const type = resp.headers.get('Content-Type');
let parsed = null;
if (type.startsWith('application/json')) {
parsed = await resp.json();
} else {
let text = await resp.text();
const parser = new DOMParser();
parsed = parser.parseFromString(text, type);
}
return parsed;
} else {
throw new Error(`${resp.url} [${resp.status} ${resp.statusText}]`);
}
}
export default class GitHub {
constructor(user, repo) {
this.user = user;
this.repo = repo;
}
static getAvatar(username, size = 80) {
const url = new URL(`${username}.png`, 'https://github.com');
const img = new Image(80, 80);
if (size) {
url.searchParams.set('size', size);
}
img.src = url;
img.alt = `${username}@GitHub`;
return img;
}
async readme() {
return get(new URL(`/repos/${this.user}/${this.repo}/readme`, ENDPOINT));
}
static async getUser(username) {
const url = new URL(`/users/${username}`, ENDPOINT);
return get(url);
}
async getContent(path) {
return get(new URL(`/repos/${this.user}/${this.repo}/contents/${path}`, ENDPOINT));
}
async getIssues(params = {}, number = null) {
let path = ['repos', this.user, this.repo, 'issues'];
if (typeof number === 'number') {
path.push(number);
}
return get(getUrl(path, params));
}
}