-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaxiosConfig.ts
More file actions
47 lines (41 loc) · 1.17 KB
/
axiosConfig.ts
File metadata and controls
47 lines (41 loc) · 1.17 KB
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
import axios, { AxiosInstance } from "axios";
import { PACKAGE_NAME, PACKAGE_VERSION } from "./contants";
import { PlainlyApiAuthenticationError, PlainlyApiError } from "./sdk/errors";
export function createApiClient(config: {
baseUrl: string;
apiKey: string;
}): AxiosInstance {
const baseUrl = config.baseUrl;
const apiKey = config.apiKey;
const instance = axios.create({
baseURL: baseUrl,
auth: {
username: apiKey,
password: "",
},
headers: {
"User-Agent": `${PACKAGE_NAME}/${PACKAGE_VERSION}`,
},
timeout: 10000,
});
// Global error handler
instance.interceptors.response.use(
(response) => response,
(error) => {
if (error.response) {
const { status, data } = error.response;
// Authentication errors
if (status === 401 || status === 403) {
return Promise.reject(new PlainlyApiAuthenticationError(status));
}
// Other API errors
if (status >= 400 && status < 600) {
return Promise.reject(new PlainlyApiError(status, data?.message));
}
}
// Network or other errors
return Promise.reject(error);
}
);
return instance;
}