2020-01-11 07:09:24 +00:00
|
|
|
export const siteUrl = window.location.protocol + '//' + window.location.hostname;
|
|
|
|
export const apiUrl = window.location.protocol + '//api.' + window.location.hostname;
|
|
|
|
export const staticUrl = window.location.protocol + '//static.' + window.location.hostname;
|
2020-01-11 06:27:30 +00:00
|
|
|
|
2020-01-08 23:43:59 +00:00
|
|
|
export const requester = (route, method, token, data) => {
|
|
|
|
let options = {headers: {}};
|
|
|
|
|
|
|
|
if (token) {
|
|
|
|
options.headers.Authorization = 'Token ' + token;
|
|
|
|
}
|
2020-01-07 07:59:12 +00:00
|
|
|
|
|
|
|
if (method == 'GET') {
|
2020-01-08 23:43:59 +00:00
|
|
|
// pass
|
|
|
|
} else if (['POST', 'PUT', 'PATCH'].includes(method)) {
|
2020-01-07 07:59:12 +00:00
|
|
|
const formData = new FormData();
|
|
|
|
Object.keys(data).forEach(key =>
|
|
|
|
formData.append(key, data[key])
|
|
|
|
);
|
|
|
|
|
|
|
|
options = {
|
2020-01-08 23:43:59 +00:00
|
|
|
...options,
|
|
|
|
method: method,
|
2020-01-07 07:59:12 +00:00
|
|
|
body: formData,
|
|
|
|
};
|
|
|
|
} else {
|
2020-01-08 23:43:59 +00:00
|
|
|
throw new Error('Method not supported');
|
2020-01-07 07:59:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const customError = (data) => {
|
|
|
|
const error = new Error(JSON.stringify(data));
|
|
|
|
error.data = data;
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
|
|
|
|
return fetch(apiUrl + route, options)
|
|
|
|
.then(response => {
|
|
|
|
if (!response.ok) {
|
|
|
|
throw customError(response);
|
|
|
|
}
|
|
|
|
return response.json();
|
|
|
|
})
|
|
|
|
.catch(error => {
|
|
|
|
const code = error.data.status;
|
|
|
|
if (code == 413) {
|
|
|
|
throw customError({non_field_errors: ['File too big']});
|
2020-01-08 23:43:59 +00:00
|
|
|
} else if (code >= 400 && code < 500) {
|
2020-01-07 07:59:12 +00:00
|
|
|
return error.data.json()
|
|
|
|
.then(result => {
|
|
|
|
throw customError(result);
|
|
|
|
});
|
2020-01-08 23:43:59 +00:00
|
|
|
} else if (code >= 500 && code < 600) {
|
|
|
|
throw customError({non_field_errors: ['Server Error']});
|
2020-01-07 07:59:12 +00:00
|
|
|
} else {
|
|
|
|
throw customError({non_field_errors: ['Network Error']});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|