forked from OpenBazaar/haven
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.js
51 lines (46 loc) · 1.34 KB
/
common.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
import { serverConfig } from '../utils/server';
import store from '../store';
export function handleFetchErrors(response) {
// Errors before logging into the server will be ignored, since those don't represent bugs.
const loggedIn = store.getState().appstate.onboardingStatus === 'loggedIn';
if (!response.ok && loggedIn) {
const errMsg = response.statusText || response.reason || '';
throw Error(`Error calling ${response.url}. Status ${response.status}. ${errMsg}`);
}
return response;
}
export function makeFetch(opts) {
const { url, method = 'GET', body = '', auth = true } = opts;
const serverAuthHeader = auth ? serverConfig.getAuthHeader() : {};
const init = {
method,
headers: {
...serverAuthHeader,
'Content-Type': 'application/json',
},
body,
};
return fetch(url, init)
.then(handleFetchErrors)
.then(response => (response.json()))
.catch((error) => {
throw error;
});
}
export const makeRequest = (apiURL, isLocal = true) => {
const authHeader = serverConfig.getAuthHeader();
const headers = {
method: 'GET',
headers: isLocal ? authHeader : {},
};
return fetch(
apiURL,
headers,
)
.then(handleFetchErrors)
.then(response => (response.json()))
.catch((err) => {
console.log(`Error with ${apiURL} is ${err}`);
return {};
});
};