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.6.0

utility-functions.md docs/

1
# Utility Functions
2
3
Helper functions for common operations including data transformation, configuration merging, adapter resolution, and concurrent request handling.
4
5
## Capabilities
6
7
### Concurrent Requests
8
9
Execute multiple requests concurrently with Promise utilities.
10
11
```typescript { .api }
12
/**
13
* Execute multiple requests concurrently
14
* @param values - Array of values or promises to resolve
15
* @returns Promise resolving to array of results
16
*/
17
function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
18
19
/**
20
* Spread array response to callback arguments
21
* @param callback - Function to receive spread arguments
22
* @returns Function that takes array and spreads it to callback
23
*/
24
function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import axios from "axios";
31
32
// Execute multiple requests concurrently
33
const requests = [
34
axios.get("https://api.example.com/users"),
35
axios.get("https://api.example.com/posts"),
36
axios.get("https://api.example.com/comments")
37
];
38
39
try {
40
const responses = await axios.all(requests);
41
const [users, posts, comments] = responses;
42
43
console.log("Users:", users.data);
44
console.log("Posts:", posts.data);
45
console.log("Comments:", comments.data);
46
} catch (error) {
47
console.error("One or more requests failed:", error);
48
}
49
50
// Using spread to handle responses
51
const handleResponses = axios.spread((users, posts, comments) => {
52
console.log("Users:", users.data);
53
console.log("Posts:", posts.data);
54
console.log("Comments:", comments.data);
55
});
56
57
axios.all([
58
axios.get("https://api.example.com/users"),
59
axios.get("https://api.example.com/posts"),
60
axios.get("https://api.example.com/comments")
61
]).then(handleResponses);
62
63
// Mixed values and promises
64
const mixed = [
65
axios.get("https://api.example.com/data"),
66
Promise.resolve({ data: "static data" }),
67
"direct value"
68
];
69
70
const results = await axios.all(mixed);
71
console.log(results); // [AxiosResponse, {data: "static data"}, "direct value"]
72
```
73
74
### Data Transformation
75
76
Convert between different data formats including FormData and JSON.
77
78
```typescript { .api }
79
/**
80
* Convert object to FormData
81
* @param sourceObj - Object to convert
82
* @param targetFormData - Existing FormData to append to
83
* @param options - Serialization options
84
* @returns FormData instance
85
*/
86
function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
87
88
/**
89
* Convert FormData or HTMLFormElement to JSON
90
* @param form - FormData or HTMLFormElement to convert
91
* @returns Plain object representation
92
*/
93
function formToJSON(form: GenericFormData | GenericHTMLFormElement): object;
94
95
interface GenericFormData {
96
append(name: string, value: any, options?: any): any;
97
}
98
99
interface GenericHTMLFormElement {
100
name: string;
101
method: string;
102
submit(): void;
103
}
104
105
interface FormSerializerOptions extends SerializerOptions {
106
// Inherits visitor, dots, metaTokens, indexes properties
107
}
108
109
interface SerializerOptions {
110
visitor?: SerializerVisitor;
111
dots?: boolean;
112
metaTokens?: boolean;
113
indexes?: boolean | null;
114
}
115
```
116
117
**Usage Examples:**
118
119
```typescript
120
import axios from "axios";
121
122
// Convert object to FormData
123
const userData = {
124
name: "John Doe",
125
email: "john@example.com",
126
age: 30,
127
preferences: {
128
theme: "dark",
129
notifications: true
130
},
131
tags: ["developer", "javascript"]
132
};
133
134
const formData = axios.toFormData(userData);
135
136
// Send as multipart/form-data
137
const response = await axios.post("https://api.example.com/users", formData, {
138
headers: {
139
"Content-Type": "multipart/form-data"
140
}
141
});
142
143
// Convert FormData back to object
144
const backToObject = axios.formToJSON(formData);
145
console.log(backToObject);
146
147
// Append to existing FormData
148
const existingFormData = new FormData();
149
existingFormData.append("existingField", "value");
150
151
const combinedFormData = axios.toFormData(userData, existingFormData);
152
153
// File upload with additional data
154
const fileData = {
155
title: "My Document",
156
description: "Document description",
157
file: fileInput.files[0],
158
metadata: {
159
category: "work",
160
tags: ["important", "draft"]
161
}
162
};
163
164
const uploadFormData = axios.toFormData(fileData);
165
const uploadResponse = await axios.post("https://api.example.com/upload", uploadFormData);
166
167
// Convert HTML form to JSON
168
const htmlForm = document.getElementById("myForm") as HTMLFormElement;
169
const formJson = axios.formToJSON(htmlForm);
170
console.log("Form data as JSON:", formJson);
171
172
// Custom serialization options
173
const customFormData = axios.toFormData(userData, undefined, {
174
dots: true, // Use dot notation for nested objects
175
indexes: true // Use array indexes
176
});
177
```
178
179
### Configuration Merging
180
181
Merge axios configurations with proper precedence and deep merging.
182
183
```typescript { .api }
184
/**
185
* Merge axios configurations
186
* @param config1 - Base configuration
187
* @param config2 - Configuration to merge
188
* @returns Merged configuration
189
*/
190
function mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig;
191
```
192
193
**Usage Examples:**
194
195
```typescript
196
import axios from "axios";
197
198
// Base configuration
199
const baseConfig = {
200
baseURL: "https://api.example.com",
201
timeout: 10000,
202
headers: {
203
"Content-Type": "application/json",
204
"User-Agent": "MyApp/1.0.0"
205
},
206
params: {
207
version: "v1"
208
}
209
};
210
211
// Request-specific configuration
212
const requestConfig = {
213
url: "/users",
214
method: "post" as const,
215
headers: {
216
"Authorization": "Bearer token123",
217
"X-Custom-Header": "value"
218
},
219
data: {
220
name: "John Doe",
221
email: "john@example.com"
222
},
223
params: {
224
include: "profile"
225
}
226
};
227
228
// Merge configurations
229
const mergedConfig = axios.mergeConfig(baseConfig, requestConfig);
230
231
console.log(mergedConfig);
232
// Result:
233
// {
234
// baseURL: "https://api.example.com",
235
// url: "/users",
236
// method: "post",
237
// timeout: 10000,
238
// headers: {
239
// "Content-Type": "application/json",
240
// "User-Agent": "MyApp/1.0.0",
241
// "Authorization": "Bearer token123",
242
// "X-Custom-Header": "value"
243
// },
244
// params: {
245
// version: "v1",
246
// include: "profile"
247
// },
248
// data: {
249
// name: "John Doe",
250
// email: "john@example.com"
251
// }
252
// }
253
254
// Use merged config in request
255
const response = await axios(mergedConfig);
256
257
// Merge multiple configurations
258
const authConfig = {
259
headers: {
260
"Authorization": "Bearer token123"
261
}
262
};
263
264
const timeoutConfig = {
265
timeout: 5000,
266
headers: {
267
"X-Timeout": "5000"
268
}
269
};
270
271
const finalConfig = axios.mergeConfig(
272
axios.mergeConfig(baseConfig, authConfig),
273
timeoutConfig
274
);
275
276
// Create reusable configuration templates
277
const createApiConfig = (endpoint: string, method: string = "get") => {
278
const endpointConfig = {
279
url: endpoint,
280
method: method as any
281
};
282
283
return axios.mergeConfig(baseConfig, endpointConfig);
284
};
285
286
const getUsersConfig = createApiConfig("/users", "get");
287
const createUserConfig = createApiConfig("/users", "post");
288
```
289
290
### Adapter Resolution
291
292
Resolve and configure request adapters for different environments.
293
294
```typescript { .api }
295
/**
296
* Resolve adapter from configuration
297
* @param adapters - Adapter configuration (name, function, or array)
298
* @returns Resolved adapter function
299
*/
300
function getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
301
302
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
303
type AxiosAdapterName = 'xhr' | 'http' | string;
304
305
interface AxiosAdapter {
306
(config: InternalAxiosRequestConfig): AxiosPromise;
307
}
308
```
309
310
**Usage Examples:**
311
312
```typescript
313
import axios from "axios";
314
315
// Get default adapter
316
const defaultAdapter = axios.getAdapter(undefined);
317
console.log("Default adapter:", defaultAdapter);
318
319
// Get specific adapter by name
320
const xhrAdapter = axios.getAdapter("xhr"); // Browser XMLHttpRequest
321
const httpAdapter = axios.getAdapter("http"); // Node.js HTTP
322
323
// Use custom adapter selection
324
const customAdapter = axios.getAdapter([
325
"xhr", // Try xhr first (browser)
326
"http", // Fallback to http (Node.js)
327
customAdapterFunction // Custom fallback
328
]);
329
330
// Create instance with specific adapter
331
const browserInstance = axios.create({
332
adapter: axios.getAdapter("xhr")
333
});
334
335
const nodeInstance = axios.create({
336
adapter: axios.getAdapter("http")
337
});
338
339
// Conditional adapter based on environment
340
const environmentAdapter = axios.getAdapter(
341
typeof window !== "undefined" ? "xhr" : "http"
342
);
343
344
const universalInstance = axios.create({
345
adapter: environmentAdapter
346
});
347
348
// Custom adapter function
349
function customAdapter(config: any) {
350
console.log("Using custom adapter for:", config.url);
351
352
return new Promise((resolve, reject) => {
353
// Custom request logic here
354
// This is a simplified example
355
fetch(config.url, {
356
method: config.method,
357
headers: config.headers,
358
body: config.data
359
})
360
.then(response => response.json())
361
.then(data => {
362
resolve({
363
data,
364
status: 200,
365
statusText: "OK",
366
headers: {},
367
config,
368
request: {}
369
});
370
})
371
.catch(reject);
372
});
373
}
374
375
// Use custom adapter
376
const customInstance = axios.create({
377
adapter: customAdapter
378
});
379
380
// Adapter middleware pattern
381
function createLoggingAdapter(baseAdapter: any) {
382
return function loggingAdapter(config: any) {
383
console.log("Request:", config.method?.toUpperCase(), config.url);
384
385
return baseAdapter(config).then(
386
(response: any) => {
387
console.log("Response:", response.status, response.config.url);
388
return response;
389
},
390
(error: any) => {
391
console.log("Error:", error.message, error.config?.url);
392
throw error;
393
}
394
);
395
};
396
}
397
398
// Wrap default adapter with logging
399
const loggingAdapter = createLoggingAdapter(axios.getAdapter(undefined));
400
401
const loggingInstance = axios.create({
402
adapter: loggingAdapter
403
});
404
```
405
406
### Version Information
407
408
Access library version information.
409
410
```typescript { .api }
411
/** Library version string */
412
const VERSION: string;
413
```
414
415
**Usage Examples:**
416
417
```typescript
418
import axios from "axios";
419
420
// Access version
421
console.log("Axios version:", axios.VERSION);
422
423
// Use in User-Agent header
424
const instance = axios.create({
425
headers: {
426
"User-Agent": `MyApp/1.0.0 (axios/${axios.VERSION})`
427
}
428
});
429
430
// Conditional behavior based on version
431
const [major, minor, patch] = axios.VERSION.split(".").map(Number);
432
433
if (major >= 1 && minor >= 6) {
434
console.log("Using modern axios features");
435
} else {
436
console.log("Using compatibility mode");
437
}
438
439
// Include in error reporting
440
function reportError(error: any) {
441
const errorReport = {
442
message: error.message,
443
url: error.config?.url,
444
method: error.config?.method,
445
axiosVersion: axios.VERSION,
446
timestamp: new Date().toISOString()
447
};
448
449
console.log("Error report:", errorReport);
450
// Send to error tracking service
451
}
452
```
453
454
### Utility Composition
455
456
Combine utility functions for complex data processing workflows.
457
458
**Usage Examples:**
459
460
```typescript
461
import axios from "axios";
462
463
// Complex data workflow
464
async function processUserData(users: any[], posts: any[]) {
465
// Convert to FormData for upload
466
const userData = {
467
users,
468
posts,
469
metadata: {
470
processedAt: new Date().toISOString(),
471
count: users.length + posts.length
472
}
473
};
474
475
const formData = axios.toFormData(userData);
476
477
// Upload processed data
478
const uploadResponse = await axios.post("https://api.example.com/batch-upload", formData);
479
480
// Convert response back to JSON if needed
481
if (uploadResponse.headers["content-type"]?.includes("multipart/form-data")) {
482
const responseJson = axios.formToJSON(uploadResponse.data);
483
return responseJson;
484
}
485
486
return uploadResponse.data;
487
}
488
489
// Batch request processor
490
async function batchRequests(configs: any[]) {
491
// Merge each config with base settings
492
const baseConfig = {
493
timeout: 10000,
494
headers: {
495
"User-Agent": `BatchProcessor/1.0.0 (axios/${axios.VERSION})`
496
}
497
};
498
499
const mergedConfigs = configs.map(config =>
500
axios.mergeConfig(baseConfig, config)
501
);
502
503
// Execute all requests
504
const requests = mergedConfigs.map(config => axios(config));
505
506
return axios.all(requests).then(
507
axios.spread((...responses) => {
508
return responses.map(response => ({
509
url: response.config.url,
510
status: response.status,
511
data: response.data
512
}));
513
})
514
);
515
}
516
517
// Usage
518
const batchConfigs = [
519
{ url: "https://api.example.com/users", method: "get" },
520
{ url: "https://api.example.com/posts", method: "get" },
521
{ url: "https://api.example.com/comments", method: "get" }
522
];
523
524
const results = await batchRequests(batchConfigs);
525
console.log("Batch results:", results);
526
527
// Form processing pipeline
528
function createFormProcessor(baseUrl: string) {
529
return {
530
async submitForm(formElement: HTMLFormElement) {
531
// Convert form to JSON
532
const formData = axios.formToJSON(formElement);
533
534
// Create request config
535
const config = axios.mergeConfig(
536
{ baseURL: baseUrl },
537
{
538
url: "/submit",
539
method: "post",
540
data: formData
541
}
542
);
543
544
return axios(config);
545
},
546
547
async uploadForm(formElement: HTMLFormElement, files: File[]) {
548
// Convert form to FormData
549
const formJson = axios.formToJSON(formElement);
550
const formData = axios.toFormData({
551
...formJson,
552
files
553
});
554
555
return axios.post(`${baseUrl}/upload`, formData, {
556
headers: { "Content-Type": "multipart/form-data" }
557
});
558
}
559
};
560
}
561
562
const processor = createFormProcessor("https://api.example.com");
563
const form = document.getElementById("myForm") as HTMLFormElement;
564
const response = await processor.submitForm(form);
565
```