2019-11-16 23:55:56 +01:00
|
|
|
import Axios from "axios";
|
|
|
|
import Notify from "common/notify";
|
2018-07-27 17:31:39 +02:00
|
|
|
|
2019-12-03 13:08:48 +01:00
|
|
|
const testConfig = {"jsHash": "test", "version": "test"};
|
|
|
|
const config = window.clientConfig ? window.clientConfig : testConfig;
|
|
|
|
|
2019-11-16 23:55:56 +01:00
|
|
|
const Api = Axios.create({
|
2019-05-09 06:48:10 +02:00
|
|
|
baseURL: "/api/v1",
|
2018-07-27 17:31:39 +02:00
|
|
|
headers: {common: {
|
2019-05-09 06:48:10 +02:00
|
|
|
"X-Session-Token": window.localStorage.getItem("session_token"),
|
2019-12-03 13:08:48 +01:00
|
|
|
"X-Client-Hash": config.jsHash,
|
|
|
|
"X-Client-Version": config.version,
|
2018-07-27 17:31:39 +02:00
|
|
|
}},
|
|
|
|
});
|
|
|
|
|
|
|
|
Api.interceptors.request.use(function (config) {
|
|
|
|
// Do something before request is sent
|
2019-11-16 23:55:56 +01:00
|
|
|
Notify.ajaxStart();
|
2018-07-27 17:31:39 +02:00
|
|
|
return config;
|
|
|
|
}, function (error) {
|
|
|
|
// Do something with request error
|
|
|
|
return Promise.reject(error);
|
|
|
|
});
|
|
|
|
|
|
|
|
Api.interceptors.response.use(function (response) {
|
2019-11-16 23:55:56 +01:00
|
|
|
Notify.ajaxEnd();
|
2019-12-03 21:25:40 +01:00
|
|
|
|
|
|
|
if(typeof response.data == "string") {
|
|
|
|
Notify.error("Request failed - invalid response");
|
2019-12-03 21:50:20 +01:00
|
|
|
console.warn("WARNING: Server returned HTML instead of JSON - API not implemented?");
|
2019-12-03 21:25:40 +01:00
|
|
|
}
|
|
|
|
|
2018-07-27 17:31:39 +02:00
|
|
|
return response;
|
|
|
|
}, function (error) {
|
2019-11-16 23:55:56 +01:00
|
|
|
Notify.ajaxEnd();
|
|
|
|
|
2019-11-17 02:11:27 +01:00
|
|
|
if (Axios.isCancel(error)) {
|
|
|
|
return Promise.reject(error);
|
|
|
|
}
|
|
|
|
|
2018-07-27 17:31:39 +02:00
|
|
|
if(console && console.log) {
|
|
|
|
console.log(error);
|
|
|
|
}
|
|
|
|
|
2019-05-09 06:48:10 +02:00
|
|
|
let errorMessage = "An error occurred - are you offline?";
|
2018-09-25 08:16:52 +02:00
|
|
|
let code = error.code;
|
|
|
|
|
|
|
|
if(error.response && error.response.data) {
|
|
|
|
let data = error.response.data;
|
|
|
|
code = data.code;
|
|
|
|
errorMessage = data.message ? data.message : data.error;
|
|
|
|
}
|
2018-07-27 17:31:39 +02:00
|
|
|
|
2019-11-23 15:09:17 +01:00
|
|
|
if (code === 401) {
|
|
|
|
Notify.logout(errorMessage);
|
|
|
|
} else {
|
|
|
|
Notify.error(errorMessage);
|
|
|
|
}
|
2018-07-27 17:31:39 +02:00
|
|
|
|
|
|
|
return Promise.reject(error);
|
|
|
|
});
|
|
|
|
|
|
|
|
export default Api;
|