-
Notifications
You must be signed in to change notification settings - Fork 7
/
fetch.worker.js
63 lines (50 loc) · 1.6 KB
/
fetch.worker.js
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
importScripts('https://unpkg.com/comlink/dist/umd/comlink.js');
class Fetch {
constructor() {
this._baseUrl = "";
this._defaultHeaders = {};
this._defaultBody = {};
}
getBaseUrl() {
return this._baseUrl;
}
getDefaultHeaders() {
return this._defaultHeaders;
}
getDefaultBody() {
return this._defaultBody;
}
setBaseUrl(baseUrl) {
this._baseUrl = baseUrl;
}
setDefaultHeaders(defaultHeaders) {
this._defaultHeaders = defaultHeaders;
}
setDefaultBody(defaultBody) {
this._defaultBody = defaultBody;
}
async get(endpoint = '') {
const response = await fetch(this.getBaseUrl() + endpoint)
const data = await response.json();
return data;
}
async post(endpoint = '', body = undefined, headers = {}) {
return await this._send('POST', endpoint, body, headers);
}
async put(endpoint = '', body = undefined, headers = {}) {
return await this._send('PUT', endpoint, body, headers);
}
async delete(endpoint = '', body = undefined, headers = {}) {
return await this._send('DELETE', endpoint, body, headers);
}
async _send(method, endpoint = '', body = undefined, headers = {}) {
const response = await fetch(this.getBaseUrl() + endpoint, {
method,
headers: { ...this.getDefaultHeaders(), ...headers },
body: JSON.stringify({ ...this.getDefaultBody(), ...body })
})
const data = await response.json();
return data;
}
}
Comlink.expose({ Fetch }, self);