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
|
import { showNotification } from "@mantine/notifications";
import Axios, { AxiosError, AxiosInstance, CancelTokenSource } from "axios";
import socketio from "@/modules/socketio";
import { notification } from "@/modules/task";
import { Environment } from "@/utilities";
import { LOG } from "@/utilities/console";
import { setAuthenticated } from "@/utilities/event";
function GetErrorMessage(data: unknown, defaultMsg = "Unknown error"): string {
if (typeof data === "string") {
return data;
} else {
return defaultMsg;
}
}
class BazarrClient {
axios!: AxiosInstance;
source!: CancelTokenSource;
bIsAuthenticated: boolean;
constructor() {
this.bIsAuthenticated = false;
const baseUrl = `${Environment.baseUrl}/api/`;
this.initialize(baseUrl, Environment.apiKey);
socketio.initialize();
}
initialize(url: string, apikey?: string) {
LOG("info", "initializing BazarrClient with baseUrl", url);
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) {
if (!this.bIsAuthenticated) {
this.bIsAuthenticated = true;
setAuthenticated(true);
}
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:
this.bIsAuthenticated = false;
setAuthenticated(false);
return;
}
LOG("error", "A error has occurred", code);
showNotification(notification.error(`Error ${code}`, message));
}
}
const client = new BazarrClient();
export default client;
|