- Spec files
npm-axios
Describes: pkg:npm/axios@1.6.x
- Description
- Promise based HTTP client for the browser and node.js
- Author
- tessl
- Last updated
utility-functions.md docs/
1# Utility Functions23Helper functions for common operations including data transformation, configuration merging, adapter resolution, and concurrent request handling.45## Capabilities67### Concurrent Requests89Execute multiple requests concurrently with Promise utilities.1011```typescript { .api }12/**13* Execute multiple requests concurrently14* @param values - Array of values or promises to resolve15* @returns Promise resolving to array of results16*/17function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;1819/**20* Spread array response to callback arguments21* @param callback - Function to receive spread arguments22* @returns Function that takes array and spreads it to callback23*/24function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;25```2627**Usage Examples:**2829```typescript30import axios from "axios";3132// Execute multiple requests concurrently33const requests = [34axios.get("https://api.example.com/users"),35axios.get("https://api.example.com/posts"),36axios.get("https://api.example.com/comments")37];3839try {40const responses = await axios.all(requests);41const [users, posts, comments] = responses;4243console.log("Users:", users.data);44console.log("Posts:", posts.data);45console.log("Comments:", comments.data);46} catch (error) {47console.error("One or more requests failed:", error);48}4950// Using spread to handle responses51const handleResponses = axios.spread((users, posts, comments) => {52console.log("Users:", users.data);53console.log("Posts:", posts.data);54console.log("Comments:", comments.data);55});5657axios.all([58axios.get("https://api.example.com/users"),59axios.get("https://api.example.com/posts"),60axios.get("https://api.example.com/comments")61]).then(handleResponses);6263// Mixed values and promises64const mixed = [65axios.get("https://api.example.com/data"),66Promise.resolve({ data: "static data" }),67"direct value"68];6970const results = await axios.all(mixed);71console.log(results); // [AxiosResponse, {data: "static data"}, "direct value"]72```7374### Data Transformation7576Convert between different data formats including FormData and JSON.7778```typescript { .api }79/**80* Convert object to FormData81* @param sourceObj - Object to convert82* @param targetFormData - Existing FormData to append to83* @param options - Serialization options84* @returns FormData instance85*/86function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;8788/**89* Convert FormData or HTMLFormElement to JSON90* @param form - FormData or HTMLFormElement to convert91* @returns Plain object representation92*/93function formToJSON(form: GenericFormData | GenericHTMLFormElement): object;9495interface GenericFormData {96append(name: string, value: any, options?: any): any;97}9899interface GenericHTMLFormElement {100name: string;101method: string;102submit(): void;103}104105interface FormSerializerOptions extends SerializerOptions {106// Inherits visitor, dots, metaTokens, indexes properties107}108109interface SerializerOptions {110visitor?: SerializerVisitor;111dots?: boolean;112metaTokens?: boolean;113indexes?: boolean | null;114}115```116117**Usage Examples:**118119```typescript120import axios from "axios";121122// Convert object to FormData123const userData = {124name: "John Doe",125email: "john@example.com",126age: 30,127preferences: {128theme: "dark",129notifications: true130},131tags: ["developer", "javascript"]132};133134const formData = axios.toFormData(userData);135136// Send as multipart/form-data137const response = await axios.post("https://api.example.com/users", formData, {138headers: {139"Content-Type": "multipart/form-data"140}141});142143// Convert FormData back to object144const backToObject = axios.formToJSON(formData);145console.log(backToObject);146147// Append to existing FormData148const existingFormData = new FormData();149existingFormData.append("existingField", "value");150151const combinedFormData = axios.toFormData(userData, existingFormData);152153// File upload with additional data154const fileData = {155title: "My Document",156description: "Document description",157file: fileInput.files[0],158metadata: {159category: "work",160tags: ["important", "draft"]161}162};163164const uploadFormData = axios.toFormData(fileData);165const uploadResponse = await axios.post("https://api.example.com/upload", uploadFormData);166167// Convert HTML form to JSON168const htmlForm = document.getElementById("myForm") as HTMLFormElement;169const formJson = axios.formToJSON(htmlForm);170console.log("Form data as JSON:", formJson);171172// Custom serialization options173const customFormData = axios.toFormData(userData, undefined, {174dots: true, // Use dot notation for nested objects175indexes: true // Use array indexes176});177```178179### Configuration Merging180181Merge axios configurations with proper precedence and deep merging.182183```typescript { .api }184/**185* Merge axios configurations186* @param config1 - Base configuration187* @param config2 - Configuration to merge188* @returns Merged configuration189*/190function mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig;191```192193**Usage Examples:**194195```typescript196import axios from "axios";197198// Base configuration199const baseConfig = {200baseURL: "https://api.example.com",201timeout: 10000,202headers: {203"Content-Type": "application/json",204"User-Agent": "MyApp/1.0.0"205},206params: {207version: "v1"208}209};210211// Request-specific configuration212const requestConfig = {213url: "/users",214method: "post" as const,215headers: {216"Authorization": "Bearer token123",217"X-Custom-Header": "value"218},219data: {220name: "John Doe",221email: "john@example.com"222},223params: {224include: "profile"225}226};227228// Merge configurations229const mergedConfig = axios.mergeConfig(baseConfig, requestConfig);230231console.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// }253254// Use merged config in request255const response = await axios(mergedConfig);256257// Merge multiple configurations258const authConfig = {259headers: {260"Authorization": "Bearer token123"261}262};263264const timeoutConfig = {265timeout: 5000,266headers: {267"X-Timeout": "5000"268}269};270271const finalConfig = axios.mergeConfig(272axios.mergeConfig(baseConfig, authConfig),273timeoutConfig274);275276// Create reusable configuration templates277const createApiConfig = (endpoint: string, method: string = "get") => {278const endpointConfig = {279url: endpoint,280method: method as any281};282283return axios.mergeConfig(baseConfig, endpointConfig);284};285286const getUsersConfig = createApiConfig("/users", "get");287const createUserConfig = createApiConfig("/users", "post");288```289290### Adapter Resolution291292Resolve and configure request adapters for different environments.293294```typescript { .api }295/**296* Resolve adapter from configuration297* @param adapters - Adapter configuration (name, function, or array)298* @returns Resolved adapter function299*/300function getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;301302type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;303type AxiosAdapterName = 'xhr' | 'http' | string;304305interface AxiosAdapter {306(config: InternalAxiosRequestConfig): AxiosPromise;307}308```309310**Usage Examples:**311312```typescript313import axios from "axios";314315// Get default adapter316const defaultAdapter = axios.getAdapter(undefined);317console.log("Default adapter:", defaultAdapter);318319// Get specific adapter by name320const xhrAdapter = axios.getAdapter("xhr"); // Browser XMLHttpRequest321const httpAdapter = axios.getAdapter("http"); // Node.js HTTP322323// Use custom adapter selection324const customAdapter = axios.getAdapter([325"xhr", // Try xhr first (browser)326"http", // Fallback to http (Node.js)327customAdapterFunction // Custom fallback328]);329330// Create instance with specific adapter331const browserInstance = axios.create({332adapter: axios.getAdapter("xhr")333});334335const nodeInstance = axios.create({336adapter: axios.getAdapter("http")337});338339// Conditional adapter based on environment340const environmentAdapter = axios.getAdapter(341typeof window !== "undefined" ? "xhr" : "http"342);343344const universalInstance = axios.create({345adapter: environmentAdapter346});347348// Custom adapter function349function customAdapter(config: any) {350console.log("Using custom adapter for:", config.url);351352return new Promise((resolve, reject) => {353// Custom request logic here354// This is a simplified example355fetch(config.url, {356method: config.method,357headers: config.headers,358body: config.data359})360.then(response => response.json())361.then(data => {362resolve({363data,364status: 200,365statusText: "OK",366headers: {},367config,368request: {}369});370})371.catch(reject);372});373}374375// Use custom adapter376const customInstance = axios.create({377adapter: customAdapter378});379380// Adapter middleware pattern381function createLoggingAdapter(baseAdapter: any) {382return function loggingAdapter(config: any) {383console.log("Request:", config.method?.toUpperCase(), config.url);384385return baseAdapter(config).then(386(response: any) => {387console.log("Response:", response.status, response.config.url);388return response;389},390(error: any) => {391console.log("Error:", error.message, error.config?.url);392throw error;393}394);395};396}397398// Wrap default adapter with logging399const loggingAdapter = createLoggingAdapter(axios.getAdapter(undefined));400401const loggingInstance = axios.create({402adapter: loggingAdapter403});404```405406### Version Information407408Access library version information.409410```typescript { .api }411/** Library version string */412const VERSION: string;413```414415**Usage Examples:**416417```typescript418import axios from "axios";419420// Access version421console.log("Axios version:", axios.VERSION);422423// Use in User-Agent header424const instance = axios.create({425headers: {426"User-Agent": `MyApp/1.0.0 (axios/${axios.VERSION})`427}428});429430// Conditional behavior based on version431const [major, minor, patch] = axios.VERSION.split(".").map(Number);432433if (major >= 1 && minor >= 6) {434console.log("Using modern axios features");435} else {436console.log("Using compatibility mode");437}438439// Include in error reporting440function reportError(error: any) {441const errorReport = {442message: error.message,443url: error.config?.url,444method: error.config?.method,445axiosVersion: axios.VERSION,446timestamp: new Date().toISOString()447};448449console.log("Error report:", errorReport);450// Send to error tracking service451}452```453454### Utility Composition455456Combine utility functions for complex data processing workflows.457458**Usage Examples:**459460```typescript461import axios from "axios";462463// Complex data workflow464async function processUserData(users: any[], posts: any[]) {465// Convert to FormData for upload466const userData = {467users,468posts,469metadata: {470processedAt: new Date().toISOString(),471count: users.length + posts.length472}473};474475const formData = axios.toFormData(userData);476477// Upload processed data478const uploadResponse = await axios.post("https://api.example.com/batch-upload", formData);479480// Convert response back to JSON if needed481if (uploadResponse.headers["content-type"]?.includes("multipart/form-data")) {482const responseJson = axios.formToJSON(uploadResponse.data);483return responseJson;484}485486return uploadResponse.data;487}488489// Batch request processor490async function batchRequests(configs: any[]) {491// Merge each config with base settings492const baseConfig = {493timeout: 10000,494headers: {495"User-Agent": `BatchProcessor/1.0.0 (axios/${axios.VERSION})`496}497};498499const mergedConfigs = configs.map(config =>500axios.mergeConfig(baseConfig, config)501);502503// Execute all requests504const requests = mergedConfigs.map(config => axios(config));505506return axios.all(requests).then(507axios.spread((...responses) => {508return responses.map(response => ({509url: response.config.url,510status: response.status,511data: response.data512}));513})514);515}516517// Usage518const 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];523524const results = await batchRequests(batchConfigs);525console.log("Batch results:", results);526527// Form processing pipeline528function createFormProcessor(baseUrl: string) {529return {530async submitForm(formElement: HTMLFormElement) {531// Convert form to JSON532const formData = axios.formToJSON(formElement);533534// Create request config535const config = axios.mergeConfig(536{ baseURL: baseUrl },537{538url: "/submit",539method: "post",540data: formData541}542);543544return axios(config);545},546547async uploadForm(formElement: HTMLFormElement, files: File[]) {548// Convert form to FormData549const formJson = axios.formToJSON(formElement);550const formData = axios.toFormData({551...formJson,552files553});554555return axios.post(`${baseUrl}/upload`, formData, {556headers: { "Content-Type": "multipart/form-data" }557});558}559};560}561562const processor = createFormProcessor("https://api.example.com");563const form = document.getElementById("myForm") as HTMLFormElement;564const response = await processor.submitForm(form);565```