-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
75 lines (66 loc) · 1.73 KB
/
Copy pathclient.ts
File metadata and controls
75 lines (66 loc) · 1.73 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
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
"use client";
import axios from "axios";
import type { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { authStoreKey } from "@/constants";
export const AXIOS_BASE = "http://178.165.121.87:8888";
const accessToken =
typeof window !== "undefined"
? JSON.parse(localStorage.getItem(authStoreKey) ?? "{}")?.state?.accessToken
: null;
const refreshToken =
typeof window !== "undefined"
? JSON.parse(localStorage.getItem(authStoreKey) ?? "{}")?.state
?.refreshToken
: null;
const AXIOS_HEADERS: AxiosRequestConfig["headers"] | undefined =
accessToken && refreshToken
? {
Authorization: `Bearer ${accessToken}`,
}
: undefined;
/**
* Subset of AxiosRequestConfig
*/
export type RequestConfig<TData = unknown> = {
url?: string;
method: "get" | "put" | "patch" | "post" | "delete";
params?: object;
data?: TData;
responseType?:
| "arraybuffer"
| "blob"
| "document"
| "json"
| "text"
| "stream";
signal?: AbortSignal;
headers?: AxiosRequestConfig["headers"];
};
/**
* Subset of AxiosResponse
*/
export type ResponseConfig<TData = unknown> = {
data: TData;
status: number;
statusText: string;
headers?: AxiosResponse["headers"];
};
export const axiosInstance = axios.create({
baseURL: typeof AXIOS_BASE !== "undefined" ? AXIOS_BASE : undefined,
headers: AXIOS_HEADERS,
});
export const axiosClient = async <
TData,
TError = unknown,
TVariables = unknown,
>(
config: RequestConfig<TVariables>,
): Promise<ResponseConfig<TData>> => {
const promise = axiosInstance
.request<TVariables, ResponseConfig<TData>>({ ...config })
.catch((e: AxiosError<TError>) => {
throw e;
});
return promise;
};
export default axiosClient;