change
This commit is contained in:
53
src/shared/api/apiClient.ts
Normal file
53
src/shared/api/apiClient.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import axios, { AxiosResponse } from "axios";
|
||||
import { API_URL } from "@/shared/constants/apiEndpoints";
|
||||
import { getLocale } from "next-intl/server";
|
||||
import { getCurrentLocale } from "@/shared/lib/getCurrentLocale";
|
||||
import { useAuthStore } from "@/shared/store/authStore";
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: API_URL || "https://api.quyoshli.uz/api",
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use(async (config) => {
|
||||
console.log("API request", config);
|
||||
const token = useAuthStore.getState().user?.access_token;
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
let language = "uz";
|
||||
try {
|
||||
language = await getLocale();
|
||||
} catch (e) {
|
||||
language = getCurrentLocale() || "uz";
|
||||
}
|
||||
|
||||
config.headers["Accept-Language"] = language;
|
||||
return config;
|
||||
});
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
console.error("API error:", error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export const GET = <T>(
|
||||
url: string,
|
||||
params?: object
|
||||
): Promise<AxiosResponse<T>> => apiClient.get(url, { params });
|
||||
export const POST = <T>(url: string, data: object): Promise<AxiosResponse<T>> =>
|
||||
apiClient.post(url, data);
|
||||
export const PUT = <T>(url: string, data: object): Promise<AxiosResponse<T>> =>
|
||||
apiClient.put(url, data);
|
||||
export const PATCH = <T>(
|
||||
url: string,
|
||||
data: object
|
||||
): Promise<AxiosResponse<T>> => apiClient.patch(url, data);
|
||||
export const DELETE = <T>(
|
||||
url: string,
|
||||
data: object
|
||||
): Promise<AxiosResponse<T>> => apiClient.delete(url, data);
|
||||
|
||||
export default apiClient;
|
||||
Reference in New Issue
Block a user