Spaces:
Sleeping
Sleeping
File size: 5,989 Bytes
d97b8f9 | 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 | # API Migration Guide: Moving to Centralized Axios Implementation
## Why Migrate?
Our project has implemented a new centralized API client using Axios interceptors which provides:
- **Centralized error handling**: Errors are handled consistently across all API calls
- **Standardized response format**: All API responses follow the same format
- **Authentication**: Automatic token management
- **Retries and token refresh**: Automatic token refresh for expired tokens
- **Progress tracking**: Built-in progress tracking for file uploads
- **Reduced code duplication**: No need to repeat the same error handling everywhere
- **Easier debugging**: All API requests go through the same pipeline, making it easier to debug
## Migration Steps
### 1. Update Imports
Replace direct Axios imports with our utility functions:
```typescript
// OLD
import axios from 'axios';
import { API_BASE_URL } from '../config';
// NEW
import { get, getList, post, put, patch, del, uploadFile } from '../lib/api/api-utils';
```
### 2. Remove API_BASE_URL from Service URLs
The base URL is already configured in the Axios instance, so you should:
```typescript
// OLD
private baseUrl = `${API_BASE_URL}/api/users`;
// NEW
private baseUrl = `/api/users`;
```
### 3. Replace Direct Axios Calls
Replace direct Axios calls with our utility functions:
#### GET Requests
```typescript
// OLD
async getItem(id: number): Promise<ResponseData<Item>> {
try {
const response = await axios.get(`${this.baseUrl}/${id}`);
return {
data: response.data,
success: true,
message: 'Item fetched successfully'
};
} catch (error: any) {
return {
data: {} as Item,
success: false,
message: error.message || 'Failed to fetch item'
};
}
}
// NEW
async getItem(id: number): Promise<ResponseData<Item>> {
return get<Item>(`${this.baseUrl}/${id}`);
}
```
#### GET List Requests
```typescript
// OLD
async getItems(): Promise<ResponseData<Item[]>> {
try {
const response = await axios.get(this.baseUrl);
return {
data: response.data,
success: true,
message: 'Items fetched successfully'
};
} catch (error: any) {
return {
data: [],
success: false,
message: error.message || 'Failed to fetch items'
};
}
}
// NEW
async getItems(): Promise<ResponseData<Item[]>> {
return getList<Item>(this.baseUrl);
}
```
#### POST Requests
```typescript
// OLD
async createItem(item: ItemCreateRequest): Promise<ResponseData<Item>> {
try {
const response = await axios.post(this.baseUrl, item, {
headers: { 'Content-Type': 'application/json' }
});
return {
data: response.data,
success: true,
message: 'Item created successfully'
};
} catch (error: any) {
return {
data: {} as Item,
success: false,
message: error.message || 'Failed to create item'
};
}
}
// NEW
async createItem(item: ItemCreateRequest): Promise<ResponseData<Item>> {
return post<Item, ItemCreateRequest>(this.baseUrl, item);
}
```
#### PUT Requests
```typescript
// OLD
async updateItem(item: ItemUpdateRequest): Promise<ResponseData<Item>> {
try {
const response = await axios.put(`${this.baseUrl}/${item.id}`, item, {
headers: { 'Content-Type': 'application/json' }
});
return {
data: response.data,
success: true,
message: 'Item updated successfully'
};
} catch (error: any) {
return {
data: {} as Item,
success: false,
message: error.message || 'Failed to update item'
};
}
}
// NEW
async updateItem(item: ItemUpdateRequest): Promise<ResponseData<Item>> {
return put<Item, ItemUpdateRequest>(`${this.baseUrl}/${item.id}`, item);
}
```
#### DELETE Requests
```typescript
// OLD
async deleteItem(id: number): Promise<ResponseData<boolean>> {
try {
await axios.delete(`${this.baseUrl}/${id}`);
return {
data: true,
success: true,
message: 'Item deleted successfully'
};
} catch (error: any) {
return {
data: false,
success: false,
message: error.message || 'Failed to delete item'
};
}
}
// NEW
async deleteItem(id: number): Promise<ResponseData<boolean>> {
return del(`${this.baseUrl}/${id}`);
}
```
#### File Uploads
```typescript
// OLD
async uploadFile(file: File, metadata: any): Promise<ResponseData<Document>> {
try {
const formData = new FormData();
formData.append('file', file);
formData.append('metadata', JSON.stringify(metadata));
const response = await axios.post(`${this.baseUrl}/upload`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
// Handle progress
}
});
return {
data: response.data,
success: true,
message: 'File uploaded successfully'
};
} catch (error: any) {
return {
data: {} as Document,
success: false,
message: error.message || 'Failed to upload file'
};
}
}
// NEW
async uploadDocument(file: File, metadata: any): Promise<ResponseData<Document>> {
return uploadFile<Document>(
`${this.baseUrl}/upload`,
file,
{ metadata: JSON.stringify(metadata) },
(progress) => {
// Handle progress
console.log(`Upload progress: ${progress}%`);
}
);
}
```
## Testing Your Migration
1. Ensure you have migrated all API calls in a service
2. Test the functionality to verify it works as expected
3. Confirm that authentication, error handling, and response formatting work correctly
## Need Help?
If you have any questions about the migration process, please refer to the full documentation in `src/lib/api/README.md` or contact the development team. |