-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
61 lines (56 loc) · 1.8 KB
/
index.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
export default class RestClient {
constructor (baseUrl = '', { headers = {}, devMode = false, simulatedDelay = 0 } = {}) {
if (!baseUrl) throw new Error('missing baseUrl');
this.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
Object.assign(this.headers, headers);
this.baseUrl = baseUrl;
this.simulatedDelay = simulatedDelay;
this.devMode = devMode;
}
_simulateDelay () {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, this.simulatedDelay);
});
}
_fullRoute (url) {
return `${this.baseUrl}${url}`;
}
_fetch (route, method, body, isQuery = false) {
if (!route) throw new Error('Route is undefined');
var fullRoute = this._fullRoute(route);
if (isQuery && body) {
var qs = require('qs');
const query = qs.stringify(body);
fullRoute = `${fullRoute}?${query}`;
body = undefined;
}
let opts = {
method,
headers: this.headers
};
if (body) {
Object.assign(opts, { body: JSON.stringify(body) });
}
const fetchPromise = () => fetch(fullRoute, opts);
const extractResponse = response =>
response.text().then(text => text? JSON.parse(text) : undefined);
if (this.devMode && this.simulatedDelay > 0) {
// Simulate an n-second delay in every request
return this._simulateDelay()
.then(() => fetchPromise())
.then(extractResponse);
} else {
return fetchPromise()
.then(extractResponse);
}
}
GET (route, query) { return this._fetch(route, 'GET', query, true); }
POST (route, body) { return this._fetch(route, 'POST', body); }
PUT (route, body) { return this._fetch(route, 'PUT', body); }
DELETE (route, query) { return this._fetch(route, 'DELETE', query, true); }
}