### Quick Start: Setup and Basic Requests Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/START-HERE.md Import the adapter, configure Axios defaults, and make basic GET and POST requests. Ensure Axios is installed and the adapter is imported correctly. ```typescript // 1. Import and setup import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' axios.defaults.adapter = createUniAppAxiosAdapter() axios.defaults.baseURL = 'https://api.example.com' // 2. Make requests const data = await axios.get('/api/users') await axios.post('/api/users', { name: 'John' }) ``` -------------------------------- ### Install @uni-helper/axios-adapter and axios Source: https://github.com/uni-helper/axios-adapter/blob/main/README.md Install the adapter and axios, ensuring their major and minor versions are consistent. For example, if using adapter v1.18.0, pair it with axios v1.18.0. ```bash pnpm i @uni-helper/axios-adapter axios ``` -------------------------------- ### Webpack Usage Example Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Example Webpack configuration including the Uni-Helper Axios Adapter plugin. ```javascript // webpack.config.js const uniAxiosAdapter = require('@uni-helper/axios-adapter/webpack') module.exports = { entry: './src/index.js', output: { filename: 'bundle.js' }, plugins: [ new uniAxiosAdapter(), ], } ``` -------------------------------- ### Install Polyfill Packages Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Install FormData and Blob polyfills for mini-program support. These are optional but recommended for full compatibility. ```bash npm install miniprogram-formdata miniprogram-blob # or with pnpm pnpm add miniprogram-formdata miniprogram-blob ``` -------------------------------- ### Install miniprogram-formdata Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Install the FormData polyfill package for mini-program compatibility. This package provides a FormData constructor compatible with Axios. ```bash npm install miniprogram-formdata ``` -------------------------------- ### Install miniprogram-blob Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Install the Blob polyfill package for mini-program compatibility. This package provides a Blob constructor compatible with Axios and standard methods. ```bash npm install miniprogram-blob ``` -------------------------------- ### Initialize Axios Adapter Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Set up the Axios adapter globally or for a specific instance. Ensure '@uni-helper/axios-adapter' and 'axios' are installed. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' // Global setup axios.defaults.adapter = createUniAppAxiosAdapter() // Instance setup const instance = axios.create({ adapter: createUniAppAxiosAdapter(), baseURL: 'https://api.example.com', timeout: 30000, }) ``` -------------------------------- ### Install Production Polyfills Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Installs the necessary polyfill packages for FormData and Blob, along with the Axios adapter, for production use. This ensures full functionality in mini-program environments. ```bash pnpm add -D miniprogram-formdata miniprogram-blob @uni-helper/axios-adapter ``` -------------------------------- ### Quick Start: File Downloads and Uploads Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/START-HERE.md Demonstrates how to use the adapter for file download and upload operations. These methods are part of the extended Axios functionality provided by the adapter. ```typescript // 3. Download/upload files const file = await axios.download('/api/file.pdf') const resp = await axios.upload('/api/upload', formData) ``` -------------------------------- ### Standard Requests Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Examples of common HTTP request methods supported by the adapter. ```APIDOC ## Standard Requests ### Description Examples of using standard HTTP methods like GET, POST, PUT, PATCH, DELETE, HEAD, and generic requests. ### GET Request ```typescript const response = await axios.get('/api/users') ``` ### POST Request ```typescript const response = await axios.post('/api/users', { name: 'John' }) ``` ### PUT Request ```typescript const response = await axios.put('/api/users/1', { name: 'Jane' }) ``` ### PATCH Request ```typescript const response = await axios.patch('/api/users/1', { active: true }) ``` ### DELETE Request ```typescript const response = await axios.delete('/api/users/1') ``` ### HEAD Request ```typescript const response = await axios.head('/api/users') ``` ### Generic Request ```typescript const response = await axios.request({ method: 'GET', url: '/api/users', timeout: 10000, }) ``` ``` -------------------------------- ### Configure Vite for Mini Programs Source: https://github.com/uni-helper/axios-adapter/blob/main/README.md Install polyfills for FormData and Blob, and enable the Vite build plugin for mini-program compatibility with FormData and Blob. ```bash pnpm add miniprogram-formdata miniprogram-blob ``` -------------------------------- ### Cancellation Examples Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/request-handler.md Illustrates how to use the Uni-Helper Axios Adapter for request cancellation with both modern AbortController and legacy CancelToken. ```APIDOC ## Cancellation via AbortController (modern) ### Description This example shows how to cancel a request using the `AbortController` API. ### Code ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() const controller = new AbortController() const promise = axios.get('/api/long-operation', { signal: controller.signal, }) setTimeout(() => controller.abort(), 5000) try { await promise } catch (error) { if (error.name === 'CanceledError') { console.log('Request was canceled') } } ``` ## Cancellation via CancelToken (legacy) ### Description This example demonstrates how to cancel a request using the legacy `CancelToken` API, compatible with older Axios versions. ### Code ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() const source = axios.CancelToken.source() const promise = axios.get('/api/data', { cancelToken: source.token, }) setTimeout(() => source.cancel('Operation timed out'), 3000) try { await promise } catch (error) { if (axios.isCancel(error)) { console.log('Request was canceled') } } ``` ``` -------------------------------- ### Vite Plugin Usage Example Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Example of how to integrate the uniAxiosAdapter into your vite.config.ts file. This plugin automatically handles environment detection and polyfill injection. ```typescript // vite.config.ts import uniAxiosAdapter from '@uni-helper/axios-adapter/vite' export default { plugins: [ uniAxiosAdapter(), ], // ... other config } ``` -------------------------------- ### Basic Setup with Global Axios Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/create-adapter.md Configure the global Axios instance to use the uni-app adapter. This allows all subsequent Axios requests to be handled by uni-app's native APIs. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' // Configure the global axios instance axios.defaults.adapter = createUniAppAxiosAdapter() // Now all requests use the uni-app adapter await axios.get('/api/users') await axios.post('/api/users', { name: 'John' }) ``` -------------------------------- ### Method Usage Example Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/types.md Example of how to define a custom request handler using the Method type. This handler can be used to customize request processing. ```typescript import type { Method } from '@uni-helper/axios-adapter' import type { AxiosRequestConfig } from 'axios' const customHandler: Method = (config, options) => { return new Promise((resolve, reject) => { // Handle request }) } ``` -------------------------------- ### Axios Authentication Examples Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates different ways to handle authentication with Axios requests, including basic authentication, token-based authentication in headers, and setting global authorization tokens. ```typescript // Basic auth await axios.get('/api/protected', { auth: { username: 'user', password: 'pass', }, }) ``` ```typescript // Token in header await axios.get('/api/protected', { headers: { Authorization: 'Bearer token123', }, }) ``` ```typescript // Global token instance.defaults.headers.common['Authorization'] = 'Bearer token123' ``` -------------------------------- ### Basic Axios Setup for Uni-App Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/README.md Configure Axios to use the Uni-App adapter and set a base URL for requests. This is typically done once at the application's entry point. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' axios.defaults.adapter = createUniAppAxiosAdapter() axios.defaults.baseURL = 'https://api.example.com' ``` -------------------------------- ### Create Axios Adapter with UserOptions Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/types.md Instantiate the adapter with an options object conforming to UserOptions. This example shows basic usage with an empty options object. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' const options: UserOptions = {} const adapter = createUniAppAxiosAdapter(options) ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Demonstrates how Axios configuration options are resolved, with per-request settings overriding instance defaults, global defaults, and adapter defaults. The default timeout for the adapter is 60000ms. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' const instance = axios.create({ adapter: createUniAppAxiosAdapter(), timeout: 20000, // Instance default }) // Global default axios.defaults.timeout = 10000 // Per-request override await instance.get('/api/data', { timeout: 5000 }) // Uses 5000ms timeout ``` -------------------------------- ### Quick Start: Error Handling Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/START-HERE.md Shows how to implement error handling for network requests, specifically catching timeout and general network errors. Use try-catch blocks to manage potential issues during requests. ```typescript // 4. Handle errors try { await axios.get('/api/data', { timeout: 5000 }) } catch (error) { if (error.code === 'ETIMEDOUT') console.log('Timeout') if (error.code === 'ERR_NETWORK') console.log('Network error') } ``` -------------------------------- ### Example Usage with FormData and Blob Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Demonstrates how to use FormData and Blob with Axios after the adapter and polyfills are configured. No additional code changes are required in your application logic. ```typescript // This works in mini-programs with the plugin const formData = new FormData() formData.append('file', new Blob(['content'])) const response = await axios.upload('/api/upload', formData) ``` -------------------------------- ### Axios Adapter Request Flow Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/README.md Illustrates the request flow managed by the createUniAppAxiosAdapter function, from initial setup to executing uni-app APIs and handling responses. ```mermaid graph TD createUniAppAxiosAdapter() ↓ [Sets up axios.upload() and axios.download() methods] [Returns AxiosAdapter function] ↓ [Axios calls adapter with AxiosRequestConfig] ↓ getMethod() — Routes by method type ├─ 'download' → uni.downloadFile() ├─ 'upload' → uni.uploadFile() └─ other → uni.request() ↓ resolveUniAppRequestOptions() — Transforms config ├─ Normalizes headers ├─ Builds full URL ├─ Handles authentication └─ Sets defaults (60s timeout) ↓ [Execute uni-app API] ↓ [Handle response/error] ├─ Map uni-app errors to Axios codes ├─ Process headers (handle DingDing format) └─ Return AxiosResponse ``` -------------------------------- ### Handle Different Method Types Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/types.md This example demonstrates how to use the MethodType discriminated union to handle different types of requests within a switch statement. ```typescript import type { MethodType } from '@uni-helper/axios-adapter' function handleRequest(methodType: MethodType) { switch (methodType) { case 'request': console.log('Standard HTTP request') break case 'download': console.log('File download') break case 'upload': console.log('File upload') break } } ``` -------------------------------- ### File Download with Timeout Handling Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/request-handler.md Implement timeout handling for file downloads to prevent excessively long operations. The example demonstrates catching a timeout error and logging a specific message. ```typescript // Download with timeout try { const response = await axios.download('/api/large.zip', { timeout: 180000, // 3 minutes }) } catch (error) { if (error.code === 'ETIMEDOUT') { console.error('Download took too long') } } ``` -------------------------------- ### Initialize Axios Adapter for UniApp Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/types.md Initializes the uni-app axios adapter by assigning it to axios.defaults.adapter. This setup allows all subsequent Axios requests to leverage uni-app's native capabilities and type-safe configurations. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() // All uni-app options are now type-safe in Axios config const response = await axios.get('/api/data', { // Axios standard properties timeout: 30000, headers: { 'X-Custom': 'value' }, // uni-app specific properties (type-safe) enableHttp2: true, enableQuic: true, enableCache: false, // uni-app callbacks (type-safe) onHeadersReceived(result) { console.log('Headers received:', result.header) }, }) ``` -------------------------------- ### Webpack Plugin Setup for Uni-App Axios Adapter Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Incorporate the uni-app Axios adapter into your Webpack or Next.js project using the provided plugin. This configuration ensures proper functioning in mini-program environments by managing polyfills and global object replacements. ```javascript // webpack.config.js or next.config.js const uniAxiosAdapter = require('@uni-helper/axios-adapter/webpack') module.exports = { plugins: [ new uniAxiosAdapter(), ], } ``` -------------------------------- ### Standard HTTP Request Methods Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Perform common HTTP requests like GET, POST, PUT, PATCH, DELETE, HEAD, and generic requests. Use 'await' for asynchronous operations. ```typescript // GET const response = await axios.get('/api/users') // POST const response = await axios.post('/api/users', { name: 'John' }) // PUT const response = await axios.put('/api/users/1', { name: 'Jane' }) // PATCH const response = await axios.patch('/api/users/1', { active: true }) // DELETE const response = await axios.delete('/api/users/1') // HEAD const response = await axios.head('/api/users') // Generic request const response = await axios.request({ method: 'GET', url: '/api/users', timeout: 10000, }) ``` -------------------------------- ### Initialization Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to globally or instance-specifically set up the uni-app axios adapter. ```APIDOC ## Initialization ### Description Global or instance setup for the uni-app axios adapter. ### Code Example ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' // Global setup axios.defaults.adapter = createUniAppAxiosAdapter() // Instance setup const instance = axios.create({ adapter: createUniAppAxiosAdapter(), baseURL: 'https://api.example.com', timeout: 30000, }) ``` ``` -------------------------------- ### Download Using axios.request() Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/axios-methods.md Demonstrates how to initiate a download using the generic `axios.request()` method by specifying the `method` as 'download'. This approach is an alternative to the dedicated `axios.download()` function. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() const response = await axios.request({ url: '/api/documents/report.xlsx', method: 'download', }) console.log('File path:', response.data) ``` -------------------------------- ### Build and Development Commands Source: https://github.com/uni-helper/axios-adapter/blob/main/AGENTS.md Common commands for building, developing, testing, type checking, linting, and running the playground. ```bash pnpm build # tsdown → dist/ (ESM + CJS + dts) pnpm dev # tsdown --watch pnpm test # vitest pnpm typecheck # tsc --noEmit pnpm lint # eslint . pnpm lint:fix # eslint . --fix pnpm play # cd playground && npm run dev:h5 ``` -------------------------------- ### Standard GET Request with Axios Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/request-handler.md Perform a standard GET request to fetch data from an API endpoint using Axios after configuring the uni.request adapter. ```typescript // Standard GET request const getResponse = await axios.get('/api/users') console.log(getResponse.status, getResponse.data) ``` -------------------------------- ### Check for Polyfill Existence Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Checks if the FormData and Blob polyfill packages are installed. If not installed, it provides empty classes to prevent errors, allowing Axios to still function but with limited FormData/Blob capabilities. ```typescript // Check if polyfills are installed const hasFormDataPolyfill = isPackageExists('miniprogram-formdata') const hasBlobPolyfill = isPackageExists('miniprogram-blob') // If installed: use them // If not installed: provide empty classes (no-op) ``` -------------------------------- ### Usage of UniNetworkRequestWithoutCallback Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/types.md Example of how to use the UniNetworkRequestWithoutCallback type for configuring network requests. Ensure all necessary properties are provided. ```typescript import type { UniNetworkRequestWithoutCallback } from '@uni-helper/axios-adapter' const config: UniNetworkRequestWithoutCallback = { url: 'https://api.example.com/data', method: 'GET', timeout: 30000, enableHttp2: true, } ``` -------------------------------- ### Making Standard, Download, and Upload Requests Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/README.md Demonstrates how to perform different types of HTTP requests using Axios with the Uni-App adapter. Includes standard GET/POST, file downloads, and file uploads. ```typescript // Standard requests (via uni.request) const response = await axios.get('/api/users') const created = await axios.post('/api/users', { name: 'John' }) // File downloads (via uni.downloadFile) const download = await axios.download('/api/file.pdf') console.log('Saved to:', download.data) // temporary file path // File uploads (via uni.uploadFile) const formData = new FormData() formData.append('file', new File([blob], 'photo.jpg')) const upload = await axios.upload('/api/photos', formData) ``` -------------------------------- ### SerializeOptions Usage Example Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/types.md Demonstrates how to use SerializeOptions to serialize an object with an array property. When `asStrings` is true, the array is converted to a comma-separated string. ```typescript import { serializeObject } from '@uni-helper/axios-adapter' import type { SerializeOptions } from '@uni-helper/axios-adapter' const options: SerializeOptions = { asStrings: true } const result = serializeObject( { tags: ['a', 'b', 'c'] }, options, ) // result: { tags: 'a, b, c' } ``` -------------------------------- ### Webpack Plugin for Axios Adapter Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/README.md Integrate the Axios adapter into your Webpack build process. This setup requires the adapter to be required and instantiated as a plugin. ```javascript const uniAxiosAdapter = require('@uni-helper/axios-adapter/webpack') module.exports = { plugins: [new uniAxiosAdapter()] } ``` -------------------------------- ### createUniAppAxiosAdapter() Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/README.md Main factory function to create an adapter instance for Axios. This function initializes the adapter and extends Axios with upload and download methods. ```APIDOC ## createUniAppAxiosAdapter() ### Description Factory function to create an Axios adapter instance specifically for uni-app environments. It sets up the adapter and extends the Axios object with `upload` and `download` methods. ### Method Factory Function ### Endpoint N/A (SDK Function) ### Parameters This function accepts an optional configuration object. Refer to the [Configuration](configuration.md) documentation for details. ### Request Example ```javascript import axios from 'axios'; import createUniAppAxiosAdapter from '@uni-helper/axios-adapter'; const adapter = createUniAppAxiosAdapter({ // Optional configuration options }); axios.defaults.adapter = adapter; // Now you can use axios for requests, including upload and download ``` ### Response Returns an Axios adapter function that can be assigned to `axios.defaults.adapter`. ``` -------------------------------- ### Handling Specific Error Codes Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/errors.md Example of how to catch errors and check for specific error codes like ETIMEDOUT or ERR_NETWORK using AxiosError constants. ```typescript import axios, { AxiosError } from 'axios' try { await axios.get('/api/data') } catch (error) { if (error.code === AxiosError.ETIMEDOUT) { console.log('Timeout') } else if (error.code === AxiosError.ERR_NETWORK) { console.log('Network error') } } ``` -------------------------------- ### Using Download and Upload Methods Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/create-adapter.md After creating the adapter, Axios instances gain `download()` and `upload()` methods. Use these for file downloads and uploads respectively. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' axios.defaults.adapter = createUniAppAxiosAdapter() // Download a file const downloadResponse = await axios.download('https://api.example.com/file.pdf') console.log(downloadResponse.data) // temporary file path // Upload a file const formData = new FormData() formData.append('file', new File([blob], 'image.jpg')) const uploadResponse = await axios.upload('https://api.example.com/upload', formData) ``` -------------------------------- ### Handling Download Errors with Axios Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/errors.md Provides an example of handling potential errors during file downloads using Axios, including timeouts and network issues. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() try { const response = await axios.download('/files/document.pdf', { timeout: 60000, }) console.log('Download saved to:', response.data) // file path } catch (error) { if (axios.isAxiosError(error)) { if (error.code === 'ETIMEDOUT') { console.error('Download timed out') } else if (error.code === 'ERR_NETWORK') { console.error('Download failed due to network error') } else { console.error('Download failed:', error.message) } } } ``` -------------------------------- ### Basic File Download Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/axios-methods.md Demonstrates how to perform a basic file download using axios.download. Ensure the axios-adapter is configured before use. The response data contains the temporary file path. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() try { const response = await axios.download('/api/files/document.pdf') console.log('File saved at:', response.data) // temporary file path } catch (error) { console.error('Download failed:', error) } ``` -------------------------------- ### Configure Axios with UniApp Adapter Source: https://github.com/uni-helper/axios-adapter/blob/main/README.md Set the default adapter for Axios to the UniApp adapter. This allows you to use Axios methods like get, post, etc., as usual. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' axios.defaults.adapter = createUniAppAxiosAdapter() ``` -------------------------------- ### Platform-Specific Options Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Enable advanced network features like HTTP/2, QUIC, HTTP DNS, and caching for potentially faster connections. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' const instance = axios.create({ adapter: createUniAppAxiosAdapter(), }) // Enable HTTP/2 and QUIC for faster connections await instance.get('/api/data', { enableHttp2: true, enableQuic: true, enableHttpDNS: true, enableCache: true, }) ``` -------------------------------- ### File Operations Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to perform file downloads and uploads, including progress tracking. ```APIDOC ## File Operations ### Description Examples for handling file downloads and uploads, including options for progress tracking and custom headers. ### Download ```typescript const response = await axios.download('/api/file.pdf') const filePath = response.data // Temporary file path ``` ### Upload ```typescript const formData = new FormData() formData.append('file', new File([blob], 'photo.jpg')) const response = await axios.upload('/api/upload', formData) ``` ### Download with Progress ```typescript await axios.download('/api/video.mp4', { onDownloadProgress(event) { console.log(`${event.loaded} / ${event.total}`) }, }) ``` ### Upload with Headers ```typescript await axios.upload('/api/upload', formData, { headers: { 'X-Auth': 'token' }, }) ``` ``` -------------------------------- ### uni.downloadFile Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/request-handler.md Executes a file download using `uni.downloadFile()`. This handler converts Axios configurations to uni-app's download format, manages the download lifecycle, maps errors, and supports progress events and cancellation. ```APIDOC ## uni.downloadFile ### Description Executes a file download using `uni.downloadFile()`. This handler converts Axios configurations to uni-app's download format, manages the download lifecycle, maps errors, and supports progress events and cancellation. ### Method POST ### Endpoint `/api/report.pdf` (Example) ### Parameters #### Query Parameters - **onDownloadProgress** (function) - Optional - Callback function to track download progress. - **timeout** (number) - Optional - Download timeout in milliseconds. #### Request Body This method does not explicitly define a request body in the provided documentation. Axios config is passed to the underlying `uni.downloadFile` function. ### Request Example ```javascript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() // Simple download const response = await axios.download('/api/report.pdf') console.log('File saved at:', response.data) // Download with progress const response = await axios.download('/api/video.mp4', { onDownloadProgress(event) { console.log(`Progress: ${Math.round(event.progress * 100)}%`) if (event.rate) { console.log(`Speed: ${event.rate} bytes/sec`) } if (event.estimated) { console.log(`ETA: ${event.estimated.toFixed(0)} seconds`) } }, }) // Download with timeout try { const response = await axios.download('/api/large.zip', { timeout: 180000, // 3 minutes }) } catch (error) { if (error.code === 'ETIMEDOUT') { console.error('Download took too long') } } ``` ### Response #### Success Response (200) - **data** (string) - The temporary file path where the downloaded file is saved. - **status** (number) - The HTTP status code of the download. - **headers** (object) - An empty object, as headers are not available from `uni.downloadFile`. #### Response Example ```json { "data": "/storage/emulated/0/Download/report.pdf", "status": 200, "headers": {} } ``` ### Error Handling Maps uni-app `errMsg` values to Axios error codes: | errMsg | Axios Code | Description | |-------------------------|-------------|---------------------------------| | `'downloadFile:fail timeout'` | `ETIMEDOUT` | Download exceeded timeout period | | `'downloadFile:fail'` | `ERR_NETWORK` | Network error or file error | | Other | `undefined` | Generic download failure | ``` -------------------------------- ### Handling Request Errors Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/README.md Implement error handling for Axios requests, specifically checking for timeouts and network errors. This example shows how to catch and differentiate common error codes. ```typescript try { await axios.get('/api/data', { timeout: 10000 }) } catch (error) { if (error.code === 'ETIMEDOUT') { console.error('Request timed out') } else if (error.code === 'ERR_NETWORK') { console.error('Network error') } else if (typeof error.code === 'number') { console.error(`HTTP ${error.code}`) } } ``` -------------------------------- ### Upload with Progress Tracking using Axios Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/axios-methods.md Illustrates uploading a file with progress tracking capabilities, although direct `onUploadProgress` is not supported. Progress information can be accessed via the response object. The uni-app Axios adapter needs to be initialized. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() const formData = new FormData() formData.append('video', new File([videoBlob], 'video.mp4')) const response = await axios.upload('/api/videos', formData, { timeout: 120000, }) console.log('Video uploaded:', response.data) ``` -------------------------------- ### Create Axios Instance with Configuration Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Create a custom axios instance with specific configurations for adapter, base URL, timeout, and headers. This allows for isolated configurations for different parts of your application. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' const instance = axios.create({ adapter: createUniAppAxiosAdapter(), baseURL: 'https://api.example.com', timeout: 30000, headers: { 'X-API-Version': '2.0', }, }) ``` -------------------------------- ### Main Factory Function Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Use this factory function to create an instance of the Axios adapter for uni-app. ```APIDOC ## createUniAppAxiosAdapter ### Description Creates an instance of the Axios adapter tailored for uni-app environments. ### Signature ```typescript function createUniAppAxiosAdapter(userOptions?: UserOptions): AxiosAdapter ``` ### Parameters - **userOptions** (UserOptions) - Optional - Configuration options for the adapter. ``` -------------------------------- ### axios.download Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/axios-methods.md Initiates a file download from a given URL. It supports standard Axios configurations and provides progress tracking via `onDownloadProgress`. ```APIDOC ## axios.download ### Description Initiates a file download from a specified URL. This method is an extension provided by the uni-helper axios adapter to facilitate file downloads within uni-app environments. ### Method Signature ```typescript axios.download, D = any>( url: string, config?: AxiosRequestConfig ): Promise ``` ### Parameters #### Path Parameters - **url** (string) - Required - The server URL to download from. Supports absolute URLs and relative paths (resolved against baseURL if configured). #### Request Body - **config** (AxiosRequestConfig) - Optional - Standard Axios configuration object. The `onDownloadProgress` property is supported for monitoring download progress. ### Response #### Success Response - **response.data** (string) - The temporary file path where the downloaded file is stored. The format and location depend on the platform (e.g., mobile app cache directory, H5 runtime). ### Throws/Rejects Rejects with `AxiosError` for network errors, timeout errors, or other failures originating from `uni.downloadFile`. ### Examples #### Basic Download ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() try { const response = await axios.download('/api/files/document.pdf') console.log('File saved at:', response.data) // temporary file path } catch (error) { console.error('Download failed:', error) } ``` #### Download with Progress Tracking ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() const response = await axios.download('/api/large-file.zip', { onDownloadProgress(progressEvent) { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ) console.log(`Download progress: ${percentCompleted}%`) console.log(`Loaded: ${progressEvent.loaded} / ${progressEvent.total}`) }, }) console.log('Download complete, file at:', response.data) ``` #### Download with Custom Timeout ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() const response = await axios.download('/api/media/video.mp4', { timeout: 120000, // 2 minutes for large files }) console.log('Video downloaded to:', response.data) ``` ``` -------------------------------- ### Create UniApp Axios Adapter Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Instantiate the adapter with an empty options object. Currently, no user options are supported, but the object is reserved for future configuration. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' const adapter = createUniAppAxiosAdapter({}) ``` -------------------------------- ### Determine Request Method Type with Axios Adapter Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/utilities.md The `getMethodType` function classifies Axios request configurations into 'request', 'download', or 'upload'. It handles case-insensitivity and defaults to 'request' (GET) if no method is specified. ```typescript import { getMethodType } from '@uni-helper/axios-adapter' getMethodType({ method: 'download', url: '/file' }) // 'download' getMethodType({ method: 'DOWNLOAD', url: '/file' }) // 'download' (case-insensitive) getMethodType({ method: 'upload', url: '/data' }) // 'upload' getMethodType({ method: 'get', url: '/data' }) // 'request' getMethodType({ url: '/data' }) // 'request' (defaults to GET) ``` -------------------------------- ### Vite Build Plugin Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Instructions for integrating the Axios adapter with Vite build tools. ```APIDOC ## Vite Plugin Integration ### Description Integrate the uni-helper Axios adapter into your Vite project by importing and using the `uniAxiosAdapter` plugin. ### Usage ```typescript // vite.config.ts import uniAxiosAdapter from '@uni-helper/axios-adapter/vite' export default { plugins: [ uniAxiosAdapter(), ], } ``` ``` -------------------------------- ### axios.download Source: https://github.com/uni-helper/axios-adapter/blob/main/README.md Initiates a download request using `uni.downloadFile`. The `response.data` is typically a file temporary path or `Buffer`. ```APIDOC ## `axios.download(url: string, config?: AxiosRequestConfig): Promise>` ### Description Initiates a download request using `uni.downloadFile`. The `response.data` is typically a file temporary path or `Buffer` (depending on the runtime environment). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### AxiosRequestConfig - `config` (AxiosRequestConfig): Optional Axios request configuration. ### Returns - `Promise>`: A promise that resolves with the Axios response. ``` -------------------------------- ### Error Handling for Network and HTTP Errors Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/request-handler.md Implement robust error handling for requests made with the uni.request adapter. This example demonstrates catching timeouts, generic network errors, and HTTP status code errors. ```typescript // Error handling try { await axios.get('/api/missing', { timeout: 5000 }) } catch (error) { if (error.code === 'ETIMEDOUT') { console.error('Request timed out') } else if (error.code === 'ERR_NETWORK') { console.error('Network error') } else if (typeof error.code === 'number') { console.error('HTTP error:', error.code, error.message) } } ``` -------------------------------- ### Override Configuration for Individual Requests Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Override default or instance configurations for specific requests by providing a configuration object as the second argument for GET requests or the third argument for POST requests. This allows for fine-grained control over individual API calls. ```typescript await axios.get('/api/data', { timeout: 60000, headers: { 'X-Custom': 'value' }, }) ``` ```typescript await axios.post('/api/users', userData, { timeout: 45000, headers: { 'X-Request-ID': id }, }) ``` -------------------------------- ### Create Custom Axios Instance Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/create-adapter.md Create a custom Axios instance with the uni-app adapter configured. This is useful for setting instance-specific configurations like baseURL and timeout. ```typescript import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' import axios from 'axios' const instance = axios.create({ adapter: createUniAppAxiosAdapter(), baseURL: 'https://api.example.com', timeout: 30000, }) const response = await instance.get('/posts') ``` -------------------------------- ### Webpack Build Plugin Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/QUICK-REFERENCE.md Instructions for integrating the Axios adapter with Webpack build tools. ```APIDOC ## Webpack Plugin Integration ### Description Integrate the uni-helper Axios adapter into your Webpack project by requiring and using the `uniAxiosAdapter` plugin. ### Usage ```javascript // webpack.config.js const uniAxiosAdapter = require('@uni-helper/axios-adapter/webpack') module.exports = { plugins: [ new uniAxiosAdapter(), ], } ``` ``` -------------------------------- ### Get Request Handler Method Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/request-handler.md Use this function to retrieve the appropriate uni-app API handler based on the Axios request configuration's method. It routes 'download' and 'upload' methods to their specific handlers, and all others to the general 'request' handler. Method names are case-insensitive. ```typescript import { getMethod } from '@uni-helper/axios-adapter/src/utils' // internal API import axios from 'axios' const downloadConfig = { method: 'download', url: '/file.pdf' } const downloadHandler = getMethod(downloadConfig) const uploadConfig = { method: 'upload', url: '/upload', data: formData } const uploadHandler = getMethod(uploadConfig) const requestConfig = { method: 'GET', url: '/api/data' } const requestHandler = getMethod(requestConfig) ``` -------------------------------- ### Create Download Progress Handler Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/utilities.md Creates a handler to normalize uni-app download progress events into AxiosProgressEvent format. Use this to process download progress updates and display information like total downloaded, progress percentage, speed, and estimated time remaining. ```typescript import { progressEventReducer } from '@uni-helper/axios-adapter' // Download progress handler const downloadProgressHandler = progressEventReducer( (event) => { console.log(`Downloaded: ${event.loaded}/${event.total}`) console.log(`Progress: ${Math.round(event.progress * 100)}%`) if (event.rate) { console.log(`Speed: ${(event.rate / 1024 / 1024).toFixed(2)} MB/s`) } if (event.estimated) { console.log(`Time remaining: ${event.estimated.toFixed(0)}s`) } }, true, // isDownloadStream ) // Use in download progress callback downloadProgressHandler({ totalBytesWritten: 1024000, totalBytesExpectedToWrite: 10240000, }) ``` -------------------------------- ### Type-Safe Configuration with TypeScript Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Illustrates how to leverage TypeScript for type-safe configuration of the Axios adapter. Custom options like `enableHttp2` are type-checked via extensions. ```typescript import axios from 'axios' import type { AxiosRequestConfig } from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' const instance = axios.create({ adapter: createUniAppAxiosAdapter(), }) // Type-checked configuration const config: AxiosRequestConfig = { url: '/api/data', method: 'GET', timeout: 30000, headers: { 'X-Custom': 'value' }, enableHttp2: true, // uni-app option (type-safe via extension) } await instance.request(config) ``` -------------------------------- ### Simple File Download Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/request-handler.md Perform a basic file download using the configured Axios adapter. The temporary file path is available in the response data upon successful completion. ```typescript // Simple download const response = await axios.download('/api/report.pdf') console.log('File saved at:', response.data) ``` -------------------------------- ### File Download with Progress Tracking Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/axios-methods.md Shows how to track the download progress of a file using the `onDownloadProgress` configuration option. This is useful for large files to provide user feedback. The `progressEvent` object contains `loaded` and `total` bytes. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' axios.defaults.adapter = createUniAppAxiosAdapter() const response = await axios.download('/api/large-file.zip', { onDownloadProgress(progressEvent) { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ) console.log(`Download progress: ${percentCompleted}%`) console.log(`Loaded: ${progressEvent.loaded} / ${progressEvent.total}`) }, }) console.log('Download complete, file at:', response.data) ``` -------------------------------- ### API with Authentication Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/configuration.md Configure an Axios instance with a base URL and timeout, then set authentication globally or per-request. ```typescript import axios from 'axios' import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter' const instance = axios.create({ adapter: createUniAppAxiosAdapter(), baseURL: 'https://api.example.com', timeout: 30000, }) // Set auth globally instance.defaults.auth = { username: 'user', password: 'pass', } // Or per-request const response = await instance.get('/protected', { auth: { username: 'user', password: 'pass' }, }) ``` -------------------------------- ### Import Webpack Plugin Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Import the Uni-Helper Axios Adapter plugin for Webpack. ```typescript const uniAxiosAdapter = require('@uni-helper/axios-adapter/webpack') ``` -------------------------------- ### axios.upload() & axios.download() Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/README.md Extended methods on the Axios instance for handling file uploads and downloads within uni-app. These methods leverage uni-app's native APIs. ```APIDOC ## axios.upload() & axios.download() ### Description These are extended methods available on the Axios instance after initializing the adapter. They provide a convenient way to perform file uploads and downloads using uni-app's native capabilities. ### Method Axios Instance Methods ### Endpoint N/A (SDK Methods) ### Parameters Both `axios.upload()` and `axios.download()` accept a configuration object similar to Axios's standard request config, with additional options specific to file operations. Refer to the [API Reference](api-reference/axios-methods.md) for detailed parameters. ### Request Example ```javascript // Upload example axios.upload('/upload', { filePath: '/path/to/file', name: 'file', formData: { userId: '123' } }) .then(response => { console.log('Upload successful:', response.data); }) .catch(error => { console.error('Upload failed:', error); }); // Download example axios.download('/download', { url: 'http://example.com/file.zip', filePath: '/path/to/save/file.zip' }) .then(response => { console.log('Download successful:', response.filePath); }) .catch(error => { console.error('Download failed:', error); }); ``` ### Response - **Success Response**: Returns a Promise that resolves with an Axios response object. For uploads, this typically contains server response data. For downloads, it might contain information about the saved file path. - **Error Response**: Returns a Promise that rejects with an error object, which can be mapped to Axios error codes. ``` -------------------------------- ### Configure Webpack Plugin Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Add the Uni-Helper Axios Adapter plugin to your Webpack configuration. ```javascript // webpack.config.js const uniAxiosAdapter = require('@uni-helper/axios-adapter/webpack') module.exports = { plugins: [ new uniAxiosAdapter(), ], } ``` -------------------------------- ### Default Timeout Configuration Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/errors.md Demonstrates making a request with the default 60-second timeout and overriding it with a custom timeout value. ```typescript // Uses 60s default timeout await axios.get('/api/data') // Override default await axios.get('/api/data', { timeout: 10000 }) ``` -------------------------------- ### Configure Vite Plugin Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/api-reference/build-plugins.md Add the uniAxiosAdapter to your Vite configuration to enable polyfill injection for mini-program environments. ```typescript // vite.config.ts import uniAxiosAdapter from '@uni-helper/axios-adapter/vite' export default { plugins: [ uniAxiosAdapter(), ], } ``` -------------------------------- ### createUniAppAxiosAdapter() Source: https://github.com/uni-helper/axios-adapter/blob/main/_autodocs/INDEX.md Main factory function to create an Axios adapter specifically for uni-app environments. This function is the primary entry point for integrating Axios with uni-app's native request APIs. ```APIDOC ## createUniAppAxiosAdapter() ### Description Creates an Axios adapter tailored for uni-app. This allows you to use Axios for making network requests within uni-app projects, leveraging uni-app's native capabilities. ### Method Factory Function ### Parameters This function accepts an optional options object to configure the adapter. ### Request Example ```javascript import axios from 'axios'; import createUniAppAxiosAdapter from '@uni-helper/axios-adapter'; const adapter = createUniAppAxiosAdapter(); axios.defaults.adapter = adapter; axios.get('/api/users').then(response => { console.log(response.data); }); ``` ### Response Returns an Axios adapter instance compatible with uni-app. ```