Initial commit: SIBU 2.0 MISSION
This commit is contained in:
59
frontend/src/services/apiClient.ts
Normal file
59
frontend/src/services/apiClient.ts
Normal file
@ -0,0 +1,59 @@
|
||||
/** Base API client for making HTTP requests to the backend */
|
||||
import axios from 'axios'
|
||||
import type { AxiosInstance, AxiosError } from 'axios'
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'
|
||||
|
||||
class ApiClient {
|
||||
private client: AxiosInstance
|
||||
|
||||
constructor() {
|
||||
this.client = axios.create({
|
||||
baseURL: API_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 10000,
|
||||
})
|
||||
|
||||
// Request interceptor
|
||||
this.client.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = localStorage.getItem('auth_token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// Response interceptor
|
||||
this.client.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error: AxiosError) => {
|
||||
// Handle common errors
|
||||
if (error.response) {
|
||||
// Server responded with error status
|
||||
console.error('API Error:', error.response.status, error.response.data)
|
||||
} else if (error.request) {
|
||||
// Request made but no response
|
||||
console.error('Network Error:', error.request)
|
||||
} else {
|
||||
// Something else happened
|
||||
console.error('Error:', error.message)
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
get instance(): AxiosInstance {
|
||||
return this.client
|
||||
}
|
||||
}
|
||||
|
||||
export const apiClient = new ApiClient().instance
|
||||
|
||||
Reference in New Issue
Block a user