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
|
import SocketIO from "@/modules/socketio";
import { notification } from "@/modules/task";
import { LOG } from "@/utilities/console";
import { setLoginRequired } from "@/utilities/event";
import { showNotification } from "@mantine/notifications";
import Axios, { AxiosError, AxiosInstance, CancelTokenSource } from "axios";
import { Environment } from "../../utilities";
function GetErrorMessage(data: unknown, defaultMsg = "Unknown error"): string {
if (typeof data === "string") {
return data;
} else {
return defaultMsg;
}
}
class BazarrClient {
axios!: AxiosInstance;
source!: CancelTokenSource;
constructor() {
const baseUrl = `${Environment.baseUrl}/api/`;
LOG("info", "initializing BazarrClient with", baseUrl);
this.initialize(baseUrl, Environment.apiKey);
SocketIO.initialize();
}
initialize(url: string, apikey?: string) {
this.axios = Axios.create({
baseURL: url,
});
this.axios.defaults.headers.post["Content-Type"] = "application/json";
this.axios.defaults.headers.common["X-API-KEY"] = apikey ?? "AUTH_NEEDED";
this.source = Axios.CancelToken.source();
this.axios.interceptors.request.use((config) => {
config.cancelToken = this.source.token;
return config;
});
this.axios.interceptors.response.use(
(resp) => {
if (resp.status >= 200 && resp.status < 300) {
return Promise.resolve(resp);
} else {
const error: BackendError = {
code: resp.status,
message: GetErrorMessage(resp.data),
};
this.handleError(error);
return Promise.reject(resp);
}
},
(error: AxiosError) => {
const message = GetErrorMessage(
error.response?.data,
"You have disconnected from the server"
);
const backendError: BackendError = {
code: error.response?.status ?? 500,
message,
};
error.message = backendError.message;
this.handleError(backendError);
return Promise.reject(error);
}
);
}
handleError(error: BackendError) {
const { code, message } = error;
switch (code) {
case 401:
setLoginRequired();
break;
}
LOG("error", "A error has occurred", code);
showNotification(notification.error(`Error ${code}`, message));
}
}
export default new BazarrClient();
|