-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathfetching.js
More file actions
69 lines (61 loc) · 1.78 KB
/
Copy pathfetching.js
File metadata and controls
69 lines (61 loc) · 1.78 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
import fetch from 'isomorphic-fetch';
import socketOptions from './socketOptions';
export function parseJSON(response) {
return response.json();
}
export function hostUrl() {
if (typeof window !== 'undefined' && window.location) {
const {origin, protocol, host} = window.location;
return origin || `${protocol}//${host}`;
}
return 'http://localhost:3000';
}
export function postJSON(route, obj) {
return fetch(hostUrl() + route, {
method: 'post',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(obj)
});
}
export function getJSON(route) {
return fetch(hostUrl() + route);
}
// export function pick(o, ...fields) {
// return Object.assign({}, ...(for (p of fields) {[p]: o[p]}));
// }
export const getClientError = errors => {
if (!errors) {
return;
}
const error = errors[0].message;
if (!error || error.indexOf('{"_error"') === -1) {
return {_error: 'Server query error'};
}
return JSON.parse(error);
};
export const prepareGraphQLParams = graphParams => {
// compress
graphParams.query = graphParams.query.replace(/\s/g, '');
return JSON.stringify(graphParams);
};
export const fetchGraphQL = async graphParams => {
const serializedParams = prepareGraphQLParams(graphParams);
const authToken = localStorage.getItem(socketOptions.authTokenName);
const currentHostUrl = hostUrl();
const graphQLUrl = `${currentHostUrl}/graphql`;
const res = await fetch(graphQLUrl, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: serializedParams
});
const resJSON = await res.json();
const {data, errors} = resJSON;
return {data, error: getClientError(errors)};
};