UNPKG

ch-chat-api-client-orval

Version:

TypeScript API client for CH Chat API with SWR hooks and Axios integration

70 lines (58 loc) 1.88 kB
import axios from "axios"; // Create a custom axios instance const axiosInstance = axios.create({ baseURL: "http://localhost:3003", // Can be overridden by setting axiosInstance.defaults.baseURL timeout: 10000, headers: { "Content-Type": "application/json", }, }); // Request interceptor axiosInstance.interceptors.request.use( (config) => { // Add auth token if available const token = localStorage.getItem("authToken"); if (token) { config.headers.Authorization = `Bearer ${token}`; } // Log request in development if (typeof window !== "undefined" && window.location.hostname === "localhost") { console.log("API Request:", config.method?.toUpperCase(), config.url); } return config; }, (error) => { return Promise.reject(error); }, ); // Response interceptor axiosInstance.interceptors.response.use( (response) => { // Log response in development if (typeof window !== "undefined" && window.location.hostname === "localhost") { console.log("API Response:", response.status, response.config.url); } return response; }, (error) => { // Handle common errors if (error.response?.status === 401) { // Handle unauthorized - redirect to login or refresh token console.error("Unauthorized access"); // You can add your auth logic here } if (error.response?.status === 403) { console.error("Forbidden access"); } if (typeof window !== "undefined" && window.location.hostname === "localhost") { console.error("API Error:", error.response?.status, error.response?.data); } return Promise.reject(error); }, ); // Export the function that orval expects export const customInstance = <T>(config: any): Promise<T> => { return axiosInstance(config); }; // Also export the instance for direct use export { axiosInstance };