File size: 6,823 Bytes
dde4052 | 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | /**
* HTTP Client with Axios
*
* Features:
* - Axios-based unified request wrapper
* - Automatic error interception and toast notifications
* - Network errors and system errors are intercepted and shown via toast
* - Only business logic errors are returned to the caller
* - Automatic 401 token expiration handling
*/
import axios, { AxiosInstance, AxiosError, AxiosResponse } from 'axios'
import { toast } from 'sonner'
/**
* Business response format - only business errors reach the caller
*/
export interface ApiResponse<T = any> {
success: boolean
data?: T
message?: string
}
/**
* HTTP Client Class
*/
export class HttpClient {
private axiosInstance: AxiosInstance
private static isHandling401 = false
constructor() {
// Create axios instance
this.axiosInstance = axios.create({
baseURL: '/',
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
})
// Setup interceptors
this.setupInterceptors()
}
/**
* Reset 401 handling flag (call after successful login)
*/
public reset401Flag(): void {
HttpClient.isHandling401 = false
}
/**
* Setup request and response interceptors
*/
private setupInterceptors(): void {
// Request interceptor - add auth token
this.axiosInstance.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 - handle errors
this.axiosInstance.interceptors.response.use(
(response: AxiosResponse) => {
// Success response - pass through
return response
},
(error: AxiosError) => {
return this.handleError(error)
}
)
}
/**
* Handle different types of errors
* Network and system errors are intercepted and shown via toast
* Only business errors are returned to caller
*/
private async handleError(error: AxiosError): Promise<any> {
// Network error (no response from server)
if (!error.response) {
toast.error('Network error - Please check your connection', {
description: 'Unable to reach the server',
})
throw new Error('Network error')
}
const { status } = error.response as AxiosResponse<{
error?: string
message?: string
}>
// Handle 401 Unauthorized
if (status === 401) {
if (HttpClient.isHandling401) {
throw new Error('Session expired')
}
HttpClient.isHandling401 = true
// Clean up
localStorage.removeItem('auth_token')
localStorage.removeItem('auth_user')
// Notify global listeners
window.dispatchEvent(new Event('unauthorized'))
// Only redirect if not already on login page
if (!window.location.pathname.includes('/login')) {
const returnUrl = window.location.pathname + window.location.search
if (returnUrl !== '/login' && returnUrl !== '/') {
sessionStorage.setItem('returnUrl', returnUrl)
}
sessionStorage.setItem('from401', 'true')
window.location.href = '/login'
// Return pending promise
return new Promise(() => {})
}
throw new Error('Session expired')
}
// Handle 403 Forbidden - system error
if (status === 403) {
toast.error('Permission Denied', {
description: 'You do not have permission to access this resource',
})
throw new Error('Permission denied')
}
// Handle 404 Not Found - system error
if (status === 404) {
toast.error('API Not Found', {
description: 'The requested endpoint does not exist (404)',
})
throw new Error('API not found')
}
// Handle 500+ Server Error - system error
if (status >= 500) {
toast.error('Server Error', {
description: 'Please try again later or contact support',
})
throw new Error('Server error')
}
// 4xx errors (except 401/403/404) are business logic errors
// Return them to the caller for handling
return Promise.reject(error)
}
/**
* Generic JSON request with standardized response
* System/network errors are already intercepted and shown via toast
* Only business errors are returned
*/
async request<T = any>(
url: string,
options: {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
data?: any
params?: any
headers?: Record<string, string>
} = {}
): Promise<ApiResponse<T>> {
try {
const response = await this.axiosInstance.request<T>({
url,
method: options.method || 'GET',
data: options.data,
params: options.params,
headers: options.headers,
})
// Success
return {
success: true,
data: response.data,
message: (response.data as any)?.message,
}
} catch (error) {
// If we get here, it's a business logic error (4xx except 401/403/404)
// System errors were already intercepted and toasted
if (axios.isAxiosError(error) && error.response) {
const errorData = error.response.data as any
return {
success: false,
message: errorData?.error || errorData?.message || 'Operation failed',
}
}
// Network error or other exception (already toasted)
throw error
}
}
/**
* GET request
*/
async get<T = any>(
url: string,
params?: any,
headers?: Record<string, string>
): Promise<ApiResponse<T>> {
return this.request<T>(url, { method: 'GET', params, headers })
}
/**
* POST request
*/
async post<T = any>(
url: string,
data?: any,
headers?: Record<string, string>
): Promise<ApiResponse<T>> {
return this.request<T>(url, { method: 'POST', data, headers })
}
/**
* PUT request
*/
async put<T = any>(
url: string,
data?: any,
headers?: Record<string, string>
): Promise<ApiResponse<T>> {
return this.request<T>(url, { method: 'PUT', data, headers })
}
/**
* DELETE request
*/
async delete<T = any>(
url: string,
headers?: Record<string, string>
): Promise<ApiResponse<T>> {
return this.request<T>(url, { method: 'DELETE', headers })
}
/**
* PATCH request
*/
async patch<T = any>(
url: string,
data?: any,
headers?: Record<string, string>
): Promise<ApiResponse<T>> {
return this.request<T>(url, { method: 'PATCH', data, headers })
}
}
// Export singleton instance
export const httpClient = new HttpClient()
// Export helper function to reset 401 flag
export const reset401Flag = () => httpClient.reset401Flag()
|