Spaces:
Sleeping
Sleeping
Centralized API Calls with Axios Interceptors
This directory contains the implementation of a centralized API client using Axios with interceptors for the PM Tool application.
Structure
axios-instance.ts: Contains the core Axios instance with configured interceptors for authentication, error handling, etc.api-utils.ts: Contains utility functions for common HTTP methods (GET, POST, PUT, PATCH, DELETE) with standardized error handling and response formatting.index.ts: Exports all API functionality for easier importing.
Features
- Authentication: Automatically adds authentication tokens to each request
- Error Handling: Centralized error handling with custom error messages
- Response Formatting: Standardized response format for all API calls
- Token Refresh: Support for token refresh flow (to be implemented)
- File Uploads: Special handling for file uploads with progress tracking
Usage
Basic API Calls
Import the API functions from the library:
import { get, getList, post, put, patch, del } from '../lib/api/api-utils';
Then use them in your service:
// GET a single item
const response = await get<User>('/api/users/1');
// GET a list of items
const response = await getList<User>('/api/users');
// POST to create a new item
const response = await post<User, UserCreateRequest>('/api/users', newUser);
// PUT to update an item
const response = await put<User, UserUpdateRequest>('/api/users/1', updatedUser);
// PATCH to partially update an item
const response = await patch<User>('/api/users/1', { name: 'Updated Name' });
// DELETE an item
const response = await del('/api/users/1');
File Uploads
import { uploadFile } from '../lib/api/api-utils';
// Upload a file with progress tracking
const response = await uploadFile(
'/api/documents',
file,
{ documentType: 'invoice' },
(progress) => {
console.log(`Upload progress: ${progress}%`);
}
);
Direct Access to Axios Instance
If you need more control, you can import the Axios instance directly:
import { apiClient } from '../lib/api';
// Use it directly
const response = await apiClient.get('/api/custom-endpoint');
Response Format
All API calls return a standardized response format:
interface ResponseData<T> {
data: T; // The actual response data
success: boolean; // Whether the request was successful
message: string; // A message describing the result
}
Error Handling
Errors are automatically handled and transformed into the same response format with:
successset tofalsedataset to a default value (empty object or array)messagecontaining the error message
Authentication
The API client automatically adds the authentication token to each request if available in localStorage.