-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapi.js
150 lines (119 loc) · 3.47 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import superagent from 'superagent';
import _ from 'lodash';
const isServer = typeof self === 'undefined';
export function appendQueryString(url, queryString) {
if (!queryString) {
return url;
}
const joinWith = url.indexOf('?') != -1 ? '&' : '?';
return `${url}${joinWith}${queryString}`;
}
export function addAuthHeaders(headers) {
const token = localStorage.getItem('jwt');
if (isServer) {
const demoToken = process.env.DEMO_AUTH_TOKEN;
if (demoToken) headers['Authorization'] = `Basic ${demoToken}`;
return;
}
if (token) headers['JWT'] = token;
}
function serialize(data) {
if (data.toJSON) data = data.toJSON();
const params = [];
for (let param in data) {
if (Object.prototype.hasOwnProperty.call(data, param)) {
const value = data[param];
if (value != null) {
const asString = _.isObject(value) ? JSON.stringify(value) : value;
params.push(encodeURIComponent(param) + '=' + encodeURIComponent(asString));
}
}
}
return params.join('&');
}
export function request(method, uri, data, options = {}) {
const isFormData = !isServer && data instanceof FormData;
let headers = {};
addAuthHeaders(headers);
if (!isFormData) {
headers['Content-Type'] = 'application/json;charset=UTF-8';
}
if (options.headers) {
headers = Object.assign(headers, options.headers);
}
// api: http://visionmedia.github.io/superagent/
const result = superagent[method.toLowerCase()](uri)
.set(headers);
if (data) {
if (method.toUpperCase() === 'GET') {
const queryString = serialize(data);
if (queryString) {
result.query(queryString);
}
} else {
result.send(data);
}
}
let error = null;
const unauthorizedHandler = options.unauthorizedHandler ? options.unauthorizedHandler : () => {
window.location.href = `${process.env.URL_PREFIX}/login`;
};
const abort = _.bind(result.abort, result);
const promise = result
.then(
(response) => {
const disposition = response.header['content-disposition'];
if (disposition && disposition.startsWith('attachment')) {
const name = disposition.split(';')[1].split('=')[1];
return {
fileName: name,
data: response.text,
};
}
return response.body;
},
(err) => {
if (err.status == 401) {
unauthorizedHandler(err.response);
}
error = new Error(_.get(err, 'message', String(err)));
error.response = err.response;
throw error;
});
// pass through abort method
promise.abort = abort;
return promise;
}
export default class Api {
static apiURI(uri) {
uri = uri.replace(/^\/api\/v\d\/|^\//, '');
uri = `/api/v1/${uri}`;
if (isServer) {
uri = `${process.env.API_URL}${uri}`;
}
return uri;
}
static request(method, uri, data, options = {}) {
return request(method, this.apiURI(uri), data, options);
}
static submitForm(form) {
const method = form.getAttribute('method');
const uri = form.getAttribute('action');
return this.request(method, uri, new FormData(form));
}
static get(...args) {
return this.request('GET', ...args);
}
static post(...args) {
return this.request('POST', ...args);
}
static delete(...args) {
return this.request('DELETE', ...args);
}
static put(...args) {
return this.request('PUT', ...args);
}
static patch(...args) {
return this.request('PATCH', ...args);
}
}