-
Notifications
You must be signed in to change notification settings - Fork 318
/
git.ts
81 lines (74 loc) · 2.06 KB
/
git.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
75
76
77
78
79
80
81
import { URLExt } from '@jupyterlab/coreutils';
import { ServerConnection } from '@jupyterlab/services';
import { ReadonlyJSONObject } from '@lumino/coreutils';
import { Git } from './tokens';
/**
* Array of Git Auth Error Messages
*/
export const AUTH_ERROR_MESSAGES = [
'Invalid username or password',
'could not read Username',
'could not read Password',
'Authentication error'
];
/**
* Call the API extension
*
* @param endPoint API REST end point for the extension; default ''
* @param method HTML method; default 'GET'
* @param body JSON object to be passed as body or null; default null
* @param namespace API namespace; default 'git'
* @returns The response body interpreted as JSON
*
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
export async function requestAPI<T>(
endPoint = '',
method = 'GET',
body: ReadonlyJSONObject | null = null,
namespace = 'git'
): Promise<T> {
// Make request to Jupyter API
const settings = ServerConnection.makeSettings();
const requestUrl = URLExt.join(
settings.baseUrl,
namespace, // API Namespace
endPoint
);
const init: RequestInit = {
method,
body: body ? JSON.stringify(body) : undefined
};
let response: Response;
try {
response = await ServerConnection.makeRequest(requestUrl, init, settings);
} catch (error) {
throw new ServerConnection.NetworkError(error);
}
let data: any = await response.text();
let isJSON = false;
if (data.length > 0) {
try {
data = JSON.parse(data);
isJSON = true;
} catch (error) {
console.log('Not a JSON response body.', response);
}
}
if (!response.ok) {
if (isJSON) {
const { message, traceback, ...json } = data;
throw new Git.GitResponseError(
response,
message ||
`Invalid response: ${response.status} ${response.statusText}`,
traceback || '',
json
);
} else {
throw new Git.GitResponseError(response, data);
}
}
return data;
}