Repository navigation
Expand file tree
/
Copy pathfetch.ts
More file actions
79 lines (70 loc) · 2.57 KB
/
Copy pathfetch.ts
File metadata and controls
79 lines (70 loc) · 2.57 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
/**
* @file github1s fetch api
* @author netcon
*/
import * as vscode from 'vscode';
import { throttle } from './func';
import { getExtensionContext } from './context';
const getGitHubAuthToken = (): string => {
const context = getExtensionContext();
return context?.globalState.get('github-oauth-token') || '';
};
export class RequestError extends Error {
constructor(message: string, public token: string) {
super(message);
if (typeof (<any>Object).setPrototypeOf === 'function') {
(<any>Object).setPrototypeOf(this, RequestError.prototype);
}
}
}
export class RequestNotFoundError extends RequestError {
constructor(message: string, token: string) {
super(message, token);
if (typeof (<any>Object).setPrototypeOf === 'function') {
(<any>Object).setPrototypeOf(this, RequestNotFoundError.prototype);
}
}
}
export class RequestRateLimitError extends RequestError {
constructor(message: string, token: string) {
super(message, token);
if (typeof (<any>Object).setPrototypeOf === 'function') {
(<any>Object).setPrototypeOf(this, RequestRateLimitError.prototype);
}
}
}
export class RequestInvalidTokenError extends RequestError {
constructor(message: string, token: string) {
super(message, token);
if (typeof (<any>Object).setPrototypeOf === 'function') {
(<any>Object).setPrototypeOf(this, RequestInvalidTokenError.prototype);
};
}
}
// only report network error once in 5 seconds
export const throttledReportNetworkError = throttle(() => vscode.window.showErrorMessage('Request Failed, Maybe an Network Error'), 5000);
export const fetch = (url: string, options?: RequestInit) => {
const token = getGitHubAuthToken();
const authHeaders = token ? { Authorization: `token ${token}` } : {};
const customHeaders = (options && 'headers' in options ? options.headers : {});
return self.fetch(url, { mode: 'cors', ...options, headers: { ...authHeaders, ...customHeaders } })
.catch(() => {
throttledReportNetworkError();
throw new RequestError('Request Failed, Maybe an Network Error', token);
})
.then(response => {
if (response.status < 400) {
return response.json();
}
if (response.status === 403) {
return response.json().then(data => { throw new RequestRateLimitError(data.message, token); });
}
if (response.status === 401) {
return response.json().then(data => { throw new RequestInvalidTokenError(data.message, token); });
}
if (response.status === 404) {
throw new RequestNotFoundError('Not Found', token);
}
throw new RequestError(`GitHub1s: Request got HTTP ${response.status} response`, token);
});
};