npm-axios

Description
Promise based HTTP client for the browser and node.js
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-axios@1.11.0

instance-management.md docs/

1
# Instance Management
2
3
Create and manage custom axios instances with their own configuration defaults, useful for different APIs, environments, or authentication schemes.
4
5
## Capabilities
6
7
### Create Custom Instance
8
9
Create a new axios instance with custom default configuration.
10
11
```javascript { .api }
12
/**
13
* Create a new axios instance with custom defaults
14
* @param config - Default configuration for the new instance
15
* @returns New axios instance with specified defaults
16
*/
17
axios.create(config?: CreateAxiosDefaults): AxiosInstance;
18
19
interface CreateAxiosDefaults {
20
baseURL?: string;
21
timeout?: number;
22
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
23
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
24
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
25
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
26
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
27
auth?: AxiosBasicCredentials;
28
responseType?: ResponseType;
29
responseEncoding?: responseEncoding;
30
xsrfCookieName?: string;
31
xsrfHeaderName?: string;
32
maxContentLength?: number;
33
maxBodyLength?: number;
34
validateStatus?: (status: number) => boolean;
35
maxRedirects?: number;
36
proxy?: AxiosProxyConfig | false;
37
// ... other AxiosRequestConfig properties
38
}
39
```
40
41
**Usage Examples:**
42
43
```javascript
44
import axios from "axios";
45
46
// API-specific instance
47
const apiClient = axios.create({
48
baseURL: "https://api.example.com/v1",
49
timeout: 10000,
50
headers: {
51
"Authorization": "Bearer your-token-here",
52
"Content-Type": "application/json"
53
}
54
});
55
56
// Different environment instances
57
const developmentAPI = axios.create({
58
baseURL: "https://dev-api.example.com",
59
timeout: 30000, // Longer timeout for dev
60
headers: { "X-Environment": "development" }
61
});
62
63
const productionAPI = axios.create({
64
baseURL: "https://api.example.com",
65
timeout: 5000,
66
headers: { "X-Environment": "production" }
67
});
68
```
69
70
### Instance Interface
71
72
Custom instances implement the same interface as the default axios instance.
73
74
```javascript { .api }
75
interface AxiosInstance extends Axios {
76
// Function call interface
77
<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
78
<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
79
80
// Create sub-instances
81
create(config?: CreateAxiosDefaults): AxiosInstance;
82
83
// Instance defaults
84
defaults: Omit<AxiosDefaults, 'headers'> & {
85
headers: HeadersDefaults & {
86
[key: string]: AxiosHeaderValue
87
}
88
};
89
90
// All HTTP methods available
91
get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
92
post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
93
put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
94
patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
95
delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
96
head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
97
options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
98
postForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
99
putForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
100
patchForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
101
}
102
```
103
104
**Usage Examples:**
105
106
```javascript
107
// Use instance like default axios
108
const users = await apiClient.get("/users");
109
const newUser = await apiClient.post("/users", userData);
110
111
// Function call interface
112
const config = { method: "get", url: "/profile" };
113
const profile = await apiClient(config);
114
115
// Create sub-instance with additional defaults
116
const adminAPI = apiClient.create({
117
headers: { "X-Admin": "true" },
118
timeout: 15000
119
});
120
```
121
122
### Axios Class
123
124
Direct instantiation of the Axios class for maximum control.
125
126
```javascript { .api }
127
/**
128
* Axios class constructor
129
* @param instanceConfig - Configuration for the instance
130
*/
131
class Axios {
132
constructor(instanceConfig?: AxiosRequestConfig);
133
134
/** Instance defaults configuration */
135
defaults: AxiosDefaults;
136
137
/** Interceptors for requests and responses */
138
interceptors: {
139
request: AxiosInterceptorManager<InternalAxiosRequestConfig>;
140
response: AxiosInterceptorManager<AxiosResponse>;
141
};
142
143
/** Core request method */
144
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
145
146
/** Generate complete request URI */
147
getUri(config?: AxiosRequestConfig): string;
148
149
// All HTTP method implementations
150
get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
151
post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
152
// ... other HTTP methods
153
}
154
```
155
156
**Usage Examples:**
157
158
```javascript
159
import { Axios } from "axios";
160
161
// Direct class instantiation
162
const customClient = new Axios({
163
baseURL: "https://custom-api.example.com",
164
timeout: 8000
165
});
166
167
// Access interceptors
168
customClient.interceptors.request.use(config => {
169
console.log("Making request to:", config.url);
170
return config;
171
});
172
173
// Generate URI without making request
174
const uri = customClient.getUri({
175
url: "/users",
176
params: { page: 1, limit: 10 }
177
});
178
console.log(uri); // "https://custom-api.example.com/users?page=1&limit=10"
179
```
180
181
### Instance Configuration Management
182
183
Modify instance defaults and access configuration.
184
185
```javascript { .api }
186
interface AxiosDefaults {
187
/** Base URL for all requests */
188
baseURL?: string;
189
/** Request timeout in milliseconds */
190
timeout: number;
191
/** Default headers for different HTTP methods */
192
headers: HeadersDefaults;
193
/** Request data transformers */
194
transformRequest: AxiosRequestTransformer[];
195
/** Response data transformers */
196
transformResponse: AxiosResponseTransformer[];
197
/** Default request adapter */
198
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
199
/** Basic authentication credentials */
200
auth?: AxiosBasicCredentials;
201
/** Default response type */
202
responseType?: ResponseType;
203
/** Maximum request/response size */
204
maxContentLength?: number;
205
maxBodyLength?: number;
206
/** Status validation function */
207
validateStatus?: (status: number) => boolean;
208
/** Maximum number of redirects */
209
maxRedirects?: number;
210
/** Proxy configuration */
211
proxy?: AxiosProxyConfig | false;
212
}
213
214
interface HeadersDefaults {
215
common: RawAxiosRequestHeaders;
216
delete: RawAxiosRequestHeaders;
217
get: RawAxiosRequestHeaders;
218
head: RawAxiosRequestHeaders;
219
post: RawAxiosRequestHeaders;
220
put: RawAxiosRequestHeaders;
221
patch: RawAxiosRequestHeaders;
222
options?: RawAxiosRequestHeaders;
223
purge?: RawAxiosRequestHeaders;
224
link?: RawAxiosRequestHeaders;
225
unlink?: RawAxiosRequestHeaders;
226
}
227
```
228
229
**Usage Examples:**
230
231
```javascript
232
// Modify instance defaults
233
const api = axios.create();
234
235
// Change base URL
236
api.defaults.baseURL = "https://new-api.example.com";
237
238
// Set common headers
239
api.defaults.headers.common["Authorization"] = "Bearer new-token";
240
241
// Set method-specific headers
242
api.defaults.headers.post["Content-Type"] = "application/json";
243
244
// Modify timeout
245
api.defaults.timeout = 15000;
246
247
// Custom status validation
248
api.defaults.validateStatus = (status) => status < 500;
249
```
250
251
### Multiple Instance Patterns
252
253
Common patterns for managing multiple API instances.
254
255
**Usage Examples:**
256
257
```javascript
258
// Service-based instances
259
const authService = axios.create({
260
baseURL: "https://auth.example.com",
261
timeout: 5000
262
});
263
264
const dataService = axios.create({
265
baseURL: "https://data.example.com",
266
timeout: 10000,
267
headers: { "Content-Type": "application/json" }
268
});
269
270
const fileService = axios.create({
271
baseURL: "https://files.example.com",
272
timeout: 30000, // Longer timeout for file operations
273
maxBodyLength: 50 * 1024 * 1024 // 50MB max file size
274
});
275
276
// Environment-based factory
277
function createAPIClient(environment) {
278
const baseURLs = {
279
development: "https://dev-api.example.com",
280
staging: "https://staging-api.example.com",
281
production: "https://api.example.com"
282
};
283
284
return axios.create({
285
baseURL: baseURLs[environment],
286
timeout: environment === "development" ? 30000 : 10000,
287
headers: {
288
"X-Environment": environment
289
}
290
});
291
}
292
293
const api = createAPIClient(process.env.NODE_ENV);
294
```