-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathGitHubClient.js
More file actions
78 lines (69 loc) · 1.84 KB
/
GitHubClient.js
File metadata and controls
78 lines (69 loc) · 1.84 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
/**
* GitHubClient
*
* Dependencies: node-fetch https://github.com/bitinn/node-fetch
*
*/
const fetch = require('node-fetch');
class HttpException extends Error {
constructor({message, status, statusText, url}) {
super(message);
this.status = status;
this.statusText = statusText;
this.url = url;
}
}
class GitHubClient {
constructor({baseUri, token}, ...features) {
this.baseUri = baseUri;
this.credentials = token !== null && token.length > 0 ? "token" + ' ' + token : null;
this.headers = {
"Content-Type": "application/json",
"Accept": "application/vnd.github.v3.full+json",
"Authorization": this.credentials
};
return Object.assign(this, ...features);
}
callGitHubAPI({method, path, data}) {
let _response = {};
return fetch(this.baseUri + path, {
method: method,
headers: this.headers,
body: data!==null ? JSON.stringify(data) : null
})
.then(response => {
_response = response;
// if response is ok transform response.text to json object
// else throw error
if (response.ok) {
return response.json()
} else {
throw new HttpException({
message: `HttpException[${method}]`,
status:response.status,
statusText:response.statusText,
url: response.url
});
}
})
.then(jsonData => {
_response.data = jsonData;
return _response;
})
}
getData({path}) {
return this.callGitHubAPI({method:'GET', path, data:null});
}
deleteData({path}) {
return this.callGitHubAPI({method:'DELETE', path, data:null});
}
postData({path, data}) {
return this.callGitHubAPI({method:'POST', path, data});
}
putData({path, data}) {
return this.callGitHubAPI({method:'PUT', path, data});
}
}
module.exports = {
GitHubClient: GitHubClient
};