-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.js
More file actions
106 lines (96 loc) · 2.56 KB
/
http.js
File metadata and controls
106 lines (96 loc) · 2.56 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* HTTP layer interface and default implementation using fetch API
*/
export class HttpLayer {
/**
* Make an HTTP POST request to the supplied URL with the given body data, and headers
* @param {string} url - the request URL
* @param {string} data - the body data
* @param {Object} headers - HTTP headers as an object to include in the request
* @param {...any} args - additional implementation-specific parameters
* @returns {HttpResponse}
*/
post(url, data, headers = {}, ...args) {
throw new Error('NotImplementedError');
}
/**
* Make an HTTP GET request to the supplied URL with the given headers
* @param {string} url - the request URL
* @param {Object} headers - HTTP headers as an object to include in the request
* @param {...any} args - additional implementation-specific parameters
* @returns {HttpResponse}
*/
get(url, headers = {}, ...args) {
throw new Error('NotImplementedError');
}
}
export class HttpResponse {
/**
* Get the value of a header from the response
* @param {string} header_name - the name of the header
* @returns {string}
*/
header(header_name) {
throw new Error('NotImplementedError');
}
/**
* Get the status code of the response
* @returns {number}
*/
get status_code() {
throw new Error('NotImplementedError');
}
}
export class RequestsHttpResponse extends HttpResponse {
/**
* Wraps the fetch Response object
* @param {Response} resp - fetch Response object
*/
constructor(resp) {
super();
this._resp = resp;
}
header(header_name) {
return this._resp.headers.get(header_name);
}
get status_code() {
return this._resp.status;
}
get fetch_response() {
return this._resp;
}
}
export class RequestsHttpLayer extends HttpLayer {
/**
* Make an HTTP POST request using fetch
* @param {string} url
* @param {string} data
* @param {Object} headers
* @param {...any} args
* @returns {Promise<RequestsHttpResponse>}
*/
async post(url, data, headers = {}, ...args) {
const resp = await fetch(url, {
method: 'POST',
body: data,
headers: headers,
...args,
});
return new RequestsHttpResponse(resp);
}
/**
* Make an HTTP GET request using fetch
* @param {string} url
* @param {Object} headers
* @param {...any} args
* @returns {Promise<RequestsHttpResponse>}
*/
async get(url, headers = {}, ...args) {
const resp = await fetch(url, {
method: 'GET',
headers: headers,
...args,
});
return new RequestsHttpResponse(resp);
}
}