This repository was archived by the owner on Jun 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathapi.js
102 lines (93 loc) · 2.93 KB
/
api.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
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
/* global fetch: true, document: true */
import cookie from 'cookie';
import {merge} from 'ramda';
import {urlBase} from '../utils';
function GET(path) {
return fetch(path, {
method: 'GET',
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': cookie.parse(document.cookie)._csrf_token,
},
});
}
function POST(path, body = {}, headers = {}) {
return fetch(path, {
method: 'POST',
credentials: 'same-origin',
headers: merge(
{
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': cookie.parse(document.cookie)._csrf_token,
},
headers
),
body: body ? JSON.stringify(body) : null,
});
}
const request = {GET, POST};
function apiThunk(endpoint, method, store, id, body, headers = {}) {
return (dispatch, getState) => {
const config = getState().config;
dispatch({
type: store,
payload: {id, status: 'loading'},
});
return request[method](`${urlBase(config)}${endpoint}`, body, headers)
.then(res => {
const contentType = res.headers.get('content-type');
if (
contentType &&
contentType.indexOf('application/json') !== -1
) {
return res.json().then(json => {
dispatch({
type: store,
payload: {
status: res.status,
content: json,
id,
},
});
return json;
});
}
return dispatch({
type: store,
payload: {
id,
status: res.status,
},
});
})
.catch(err => {
/* eslint-disable no-console */
console.error(err);
/* eslint-enable no-console */
dispatch({
type: store,
payload: {
id,
status: 500,
},
});
});
};
}
export function getLayout() {
return apiThunk('_dash-layout', 'GET', 'layoutRequest');
}
export function getDependencies() {
return apiThunk('_dash-dependencies', 'GET', 'dependenciesRequest');
}
export function login(oauth_token) {
return apiThunk('_dash-login', 'POST', 'loginRequest', '', '', {
Authorization: `Bearer ${oauth_token}`,
});
}
export function getReloadHash() {
return apiThunk('_reload-hash', 'GET', 'reloadRequest');
}