### Complete Alova Instance Configuration Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/configuration.md Demonstrates a comprehensive setup for an Alova instance, including global configuration, instance settings, caching, and lifecycle hooks. ```typescript import { createAlova } from 'alova'; import { useRequest } from '@alova/client'; import fetchAdapter from 'alova/fetch'; import { localStorageAdapter, memoryAdapter } from 'alova'; // Set global config import globalConfig from 'alova'; globalConfig({ autoHitCache: 'global', ssr: false }); // Create configured instance const alova = createAlova({ // Identification id: 'main-api', // Base URL baseURL: 'https://api.example.com', // Request adapter requestAdapter: fetchAdapter(), // Timeout timeout: 30000, // State management // statesHook auto-detected in Vue/React context // Caching cacheFor: { GET: 300000, // 5 min POST: 0, // No cache PUT: { expire: 600000, mode: 'restore' } }, l1Cache: memoryAdapter(), l2Cache: localStorageAdapter(), // Request sharing shareRequest: true, // Snapshots snapshots: 1000, // Lifecycle hooks beforeRequest: async (method) => { const token = await getAuthToken(); method.config.headers.Authorization = `Bearer ${token}`; }, responded: { onSuccess: (response) => { // Transform response if (response.code === 0) { return response.data; } throw new Error(response.message); }, onError: (error) => { // Log errors console.error('API Error:', error); } }, // Logging cacheLogger: true }); // Use in components function UserList() { const { data, loading, error } = useRequest( () => alova.Get('/users'), { immediate: true } ); return (
{loading &&

Loading...

} {error &&

Error: {error.message}

} {data && data.map(user =>
{user.name}
)}
); } ``` -------------------------------- ### Fetch Adapter Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Demonstrates creating an Alova instance with the fetch adapter and performing a simple GET request and a file upload with progress tracking. ```typescript const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: fetchAdapter(), beforeRequest: (method) => { method.config.headers.Authorization = `Bearer ${token}`; } }); // Simple request const userData = await alova.Get('/users/123').send(); // File upload with progress const formData = new FormData(); formData.append('file', fileInput.files[0]); const uploadMethod = alova.Post('/upload', formData); uploadMethod.onUpload(({ loaded, total }) => { console.log(`Uploaded ${loaded}/${total}`); }); const result = await uploadMethod.send(); ``` -------------------------------- ### Install Axios Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Install the axios adapter along with the axios library. ```bash npm install @alova/adapter-axios axios ``` -------------------------------- ### Install XHR Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Install the xhr adapter for browser-based requests. ```bash npm install @alova/adapter-xhr ``` -------------------------------- ### Mock Adapter Basic Usage Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Configure the mock adapter with an array of mock response rules. This example sets up mock responses for GET and POST requests to '/users' with a 100ms delay. ```typescript import { createAlova } from 'alova'; import mockAdapter from '@alova/adapter-mock'; const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: mockAdapter([ { url: '/users', method: 'GET', status: 200, response: { data: [{ id: 1, name: 'John' }] } }, { url: '/users', method: 'POST', status: 201, response: (req) => ({ id: 2, ...req.data }) } ], 100) // 100ms delay }); ``` -------------------------------- ### Mock Adapter Installation Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Install the mock adapter for Alova to mock HTTP responses during testing. ```bash npm install @alova/adapter-mock ``` -------------------------------- ### Install Alova with Fetch Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs Alova along with the recommended Fetch adapter. This is suitable for most browser-based applications. ```bash # Fetch adapter (recommended for most projects) npm install alova ``` -------------------------------- ### Install Fetch Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md The fetch adapter is included with alova and requires no separate installation. ```bash # Included with alova npm install alova ``` -------------------------------- ### Install Node.js HTTP Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Install the http adapter for server-side requests in Node.js environments. ```bash npm install @alova/adapter-http ``` -------------------------------- ### Install Alova Core Package Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs the core Alova library using npm. This is the first step for any Alova project. ```bash npm install alova ``` -------------------------------- ### XHR Adapter Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Shows how to use the xhr adapter to track upload progress and abort a request. ```typescript const method = alova.Post('/upload', formData); // Track upload progress method.onUpload(({ loaded, total }) => { const percent = ((loaded / total) * 100).toFixed(0); console.log(`Upload: ${percent}%`); }); // Abort request setTimeout(() => { method.abort(); }, 5000); await method.send(); ``` -------------------------------- ### Complete Server Example with Hooks Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/server-hooks.md An example demonstrating the integration of multiple server-side hooks including rate limiting, atomic locks, and retries within an Express middleware. ```typescript import { createAlova } from 'alova'; import { atomize, createRateLimiter, retry } from 'alova/server'; import nodeAdapter from '@alova/adapter-http'; const alovaInstance = createAlova({ baseURL: 'https://api.example.com', requestAdapter: nodeAdapter() }); // Create rate limiter for user IP const limiter = createRateLimiter({ points: 100, duration: 3600000 }); // Express middleware app.get('/api/data/:id', async (req, res) => { let method = alovaInstance.Get(`/data/${req.params.id}`); // Apply rate limiting by IP method = limiter(method, { key: `ip:${req.ip}` }); // Apply atomic lock to prevent cache stampede method = atomize(method, { channel: `data-${req.params.id}`, timeout: 5000 }); // Apply retry with exponential backoff method = retry(method, { retry: 3, backoff: { initialDelay: 1000, maxDelay: 10000, multiplier: 2 } }); try { const data = await method.send(); res.json(data); } catch (error) { if (error.status === 429) { res.status(429).json({ error: 'Too many requests' }); } else { res.status(500).json({ error: 'Request failed' }); } } }); ``` -------------------------------- ### Install Alova for React Integration Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs Alova for integration with React applications. This setup is optimized for use with React Hooks. ```bash # React npm install alova ``` -------------------------------- ### UniApp Adapter Installation Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Install the UniApp adapter for Alova to integrate it into UniApp projects. ```bash npm install @alova/adapter-uniapp ``` -------------------------------- ### Install Alova with Axios Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs Alova and the Axios adapter, along with Axios itself. Use this if your project already relies on Axios or prefers its features. ```bash # Axios adapter npm install alova @alova/adapter-axios axios ``` -------------------------------- ### Install Alova for Nuxt 3 Integration Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs Alova for integration with Nuxt 3 projects. This setup is optimized for server-side rendering and Nuxt's ecosystem. ```bash # Nuxt 3 npm install alova ``` -------------------------------- ### Create GET Request Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Use the `Get` method to create a GET request. You can specify the URL and optional configuration such as headers, parameters, and cache settings. ```typescript const userMethod = alovaInstance.Get('/api/user/123', { headers: { Authorization: 'Bearer token' } }); const user = await userMethod.send(); ``` -------------------------------- ### Install Alova for Svelte Integration Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs Alova for integration with Svelte projects. This setup is optimized for use with Svelte Stores. ```bash # Svelte npm install alova ``` -------------------------------- ### Install Alova with Node.js HTTP Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs Alova and the Node.js HTTP adapter for server-side requests. Essential for SSR or backend applications. ```bash # Node.js HTTP adapter npm install alova @alova/adapter-http ``` -------------------------------- ### Coordinated User Updates Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md A complete example demonstrating coordinated updates for user management, including optimistic UI updates, request sending, and state reversion on error. ```typescript import { createAlova } from 'alova'; import { useRequest, updateState } from '@alova/client'; import fetchAdapter from 'alova/fetch'; const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: fetchAdapter() }); export function UserManagement() { // List users const { data: users, send: refreshUsers } = useRequest( () => alova.Get('/users') ); // Create user const { send: createUser } = useRequest( (userData) => alova.Post('/users', userData), { immediate: false } ); const handleCreateUser = async (newUserData) => { try { // Optimistically update UI await updateState( alova.Get('/users'), (oldUsers) => [ ...oldUsers, { id: 'temp', ...newUserData } ] ); // Send request const result = await createUser(newUserData); // Update with actual data await updateState( alova.Get('/users'), (oldUsers) => [ ...oldUsers.filter(u => u.id !== 'temp'), result ] ); } catch (error) { // Revert on error await refreshUsers(); } }; return (
{users?.map(user => (
{user.name}
))}
); } ``` -------------------------------- ### Mock Adapter with Vitest Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md This example demonstrates using the mock adapter within Vitest for comprehensive API testing. It includes tests for fetching, creating, and handling errors. ```typescript import { createAlova } from 'alova'; import mockAdapter from '@alova/adapter-mock'; import { describe, it, expect } from 'vitest'; describe('User API', () => { const alova = createAlova({ requestAdapter: mockAdapter([ { url: /^\/users\/\d+$/, method: 'GET', status: 200, response: { id: 1, name: 'John' } }, { url: '/users', method: 'POST', status: 201, response: (req) => ({ id: 2, ...req.data, createdAt: new Date().toISOString() }) }, { url: '/error-endpoint', method: 'GET', status: 500, response: { error: 'Server error' } } ]) }); it('should fetch user', async () => { const user = await alova.Get('/users/1').send(); expect(user.name).toBe('John'); }); it('should create user', async () => { const user = await alova.Post('/users', { name: 'Jane' }).send(); expect(user.id).toBe(2); expect(user.name).toBe('Jane'); }); it('should handle errors', async () => { try { await alova.Get('/error-endpoint').send(); } catch (error) { expect(error.status).toBe(500); } }); }); ``` -------------------------------- ### Axios Adapter Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Demonstrates configuring a custom Axios instance with interceptors and then using it with the Alova axios adapter for requests. ```typescript const axiosInstance = axios.create({ timeout: 30000, headers: { 'Content-Type': 'application/json' } }); // Add interceptor axiosInstance.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${getToken()}`; return config; }); const alova = createAlova({ requestAdapter: axiosAdapter({ axiosInstance }) }); // Use with Alova const response = await alova.Post('/login', { email, password }).send(); ``` -------------------------------- ### Taro Adapter Installation Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Install the Taro adapter for Alova to use it within Taro framework projects. ```bash npm install @alova/adapter-taro ``` -------------------------------- ### Constructor Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/method-class.md Initializes a Method instance. Typically created via Alova instance methods (Get, Post, etc.) rather than directly. ```APIDOC ## Constructor Initializes a Method instance. Typically created via Alova instance methods (Get, Post, etc.) rather than directly. ### Method Signature ```typescript constructor( type: MethodType, context: Alova, url: string, config?: AlovaMethodCreateConfig, data?: RequestBody ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Constructor Parameters - **type** (`MethodType`) - Required - HTTP method type (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) - **context** (`Alova`) - Required - Parent Alova instance - **url** (`string`) - Required - Request URL - **config** (`AlovaMethodCreateConfig`) - Optional - Optional configuration for this request - **data** (`RequestBody`) - Optional - Request body (for POST, PUT, PATCH, etc.) ``` -------------------------------- ### Alova Class - Get Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Creates a GET request to a specified URL. Accepts optional configuration for headers, parameters, and cache settings. Returns a Method instance for the GET request. ```APIDOC ## Alova Class - Get Method ### Description Creates a GET request. ### Signature ```typescript Get( url: string, config?: AlovaMethodCreateConfig ): Method> ``` ### Parameters #### url - **url** (`string`) - Required - The request URL #### config - **config** (`AlovaMethodCreateConfig`) - Optional - Optional configuration (headers, params, cache settings, etc.) ### Return Type A `Method` instance for the GET request. ### Usage Example ```typescript const userMethod = alovaInstance.Get('/api/user/123', { headers: { Authorization: 'Bearer token' } }); const user = await userMethod.send(); ``` ``` -------------------------------- ### Basic GET and POST Request Handling Source: https://github.com/alovajs/alova/blob/main/examples/server/views/basic.html This snippet shows how to initiate GET and POST requests and update UI elements. It's useful for simple data fetching and submission scenarios. Ensure the Alova instance is correctly configured before use. ```javascript const request = async (button, method) => { button.setAttribute('disabled', 'disabled'); try { const res = await method; const divEl = document.createElement('div'); divEl.innerHTML = JSON.stringify(res); dashboard.appendChild(divEl); } finally { button.removeAttribute('disabled'); } }; on('#btnGet', 'click', async () => { request( btnGet, alovaInstance.Get('/api/basic', { cacheFor: null }) ); }); on('#btnPost', 'click', async () => { request( btnPost, alovaInstance.Post('/api/basic', { cacheFor: null }) ); }); ``` -------------------------------- ### useFetcher Usage Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/client-hooks.md Demonstrates how to use the useFetcher hook to manually trigger data fetching. It includes handling loading states, displaying fetched data, and managing errors. ```typescript import { useFetcher } from '@alova/client'; function PrefetchButtons() { const { fetch, loading, data, error } = useFetcher({ updateState: true }); const handlePrefetch = async (userId) => { const result = await fetch( alovaInstance.Get(`/api/users/${userId}`) ); console.log('Prefetched:', result); }; return (
{loading && 'Fetching...'} {data &&

Last fetch: {JSON.stringify(data)}

} {error &&

Error: {error.message}

}
); } ``` -------------------------------- ### useWatcher Usage Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/client-hooks.md Shows how to use the useWatcher hook to automatically send requests when watched state values change. This example configures immediate execution, debouncing, and aborting previous requests. ```typescript import { useWatcher } from '@alova/client'; function SearchResults({ keywords, category }) { const { data, loading, error, send } = useWatcher( () => alovaInstance.Get('/api/search', { params: { q: keywords, category } }), [keywords, category], { immediate: true, debounce: 500, // Wait 500ms after change before sending abortLast: true // Cancel previous request } ); return (
{loading && 'Searching...'} {data && data.results.map(item =>
{item.name}
)} {error &&

Search failed

}
); } ``` -------------------------------- ### useRequest Hook Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/client-hooks.md This React example demonstrates how to use the `useRequest` hook to fetch user profile data. It automatically manages loading, data, and error states, and provides functions to manually send requests or abort them. The hook is configured to fetch immediately on mount and uses an initial data value. ```typescript import { useRequest } from '@alova/client'; // React example function UserProfile({ userId }) { const { data, loading, error, send, abort } = useRequest( () => alovaInstance.Get(`/api/users/${userId}`), { immediate: true, initialData: { name: 'Loading...' } } ); return (
{loading ? 'Loading...' : `User: ${data.name}`} {error &&

Error: {error.message}

}
); } ``` -------------------------------- ### Install Alova for Vue 3 Integration Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Installs Alova for seamless integration with Vue 3 projects. This typically includes the core library and framework-specific bindings. ```bash # Vue 3 npm install alova ``` -------------------------------- ### Express Middleware Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md This snippet shows how to use the httpAdapter in an Express.js application to proxy requests to another URL. ```typescript // Express middleware app.get('/api/proxy', async (req, res) => { const alova = createAlova({ requestAdapter: httpAdapter() }); const data = await alova.Get(req.query.url).send(); res.json(data); }); ``` -------------------------------- ### Switch Adapters at Runtime Based on Environment Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md This example demonstrates how to dynamically select an Alova request adapter based on the runtime environment (server-side vs. browser). It imports both the fetch adapter for browsers and the http adapter for Node.js. ```typescript import { createAlova } from 'alova'; import fetchAdapter from 'alova/fetch'; import nodeAdapter from '@alova/adapter-http'; const isServer = typeof window === 'undefined'; const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: isServer ? nodeAdapter() : fetchAdapter() }); ``` -------------------------------- ### Method Constructor Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/method-class.md Initializes a Method instance. This is typically created via Alova instance methods (e.g., Get, Post) rather than directly. ```typescript constructor( type: MethodType, context: Alova, url: string, config?: AlovaMethodCreateConfig, data?: RequestBody ) ``` -------------------------------- ### Per-Method Cache Settings Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/cache-management.md Examples of configuring cache for individual methods, including dynamic caching, specific expiration dates, no caching, and indefinite caching. ```typescript // Controlled cache (function-based) const method = alovaInstance.Get('/api/dynamic', { cacheFor: () => { return Date.now() % 2 === 0 ? 300000 : 0; // Randomly cache or not } }); // Expire at specific date const method2 = alovaInstance.Get('/api/data', { cacheFor: { expire: new Date('2025-12-31'), mode: 'restore' } }); // No cache const method3 = alovaInstance.Post('/api/form', data, { cacheFor: 0 }); // Cache forever const method4 = alovaInstance.Get('/api/constants', { cacheFor: Infinity }); ``` -------------------------------- ### Custom Adapter Template Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md A template for creating a custom Alova request adapter. This example outlines the structure for implementing request logic, handling responses, and managing abort/progress callbacks. ```typescript export default function myCustomAdapter(config?: CustomConfig): AlovaRequestAdapter { return (elements, method) => { const { url, type, headers, data } = elements; const fullUrl = method.context.options.baseURL + url; let abort = () => {}; let downloadHandler: ProgressUpdater | undefined; let uploadHandler: ProgressUpdater | undefined; return { response: async () => { // Implement actual HTTP request const response = await myHttpClient.request({ url: fullUrl, method: type, headers, data, onDownload: (loaded, total) => { downloadHandler?.({ loaded, total }); }, onUpload: (loaded, total) => { uploadHandler?.({ loaded, total }); }, onAbort: () => { abort(); } }); return response.data; }, headers: async () => { // Return response headers return {}; }, onDownload: (handler) => { downloadHandler = handler; }, onUpload: (handler) => { uploadHandler = handler; }, abort: () => { // Cancel the request } }; }; } ``` -------------------------------- ### Create Multiple Alova Instances with Different Adapters Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md This snippet shows how to create separate Alova instances, each configured with a different request adapter. This is useful when you need to manage distinct API clients, for example, one for client-side requests and another for server-side requests. ```typescript const clientAlova = createAlova({ requestAdapter: fetchAdapter() }); const serverAlova = createAlova({ requestAdapter: nodeAdapter() }); ``` -------------------------------- ### Create General Request Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Use the `Request` method to create a generic HTTP request with flexible configuration. This is useful for methods other than GET or POST, or when more complex configurations are needed. ```typescript const method = alovaInstance.Request({ method: 'POST', url: '/api/users', data: { name: 'John' } }); await method.send(); ``` -------------------------------- ### Options Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Creates an OPTIONS request to the specified URL with optional configuration. Returns a Method instance for the OPTIONS request. ```APIDOC ## Options ### Description Creates an OPTIONS request. ### Method OPTIONS ### Endpoint `/url` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response Returns a `Method` instance for the OPTIONS request. ``` -------------------------------- ### Create Alova Instance with Fetch Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Initialize Alova with the fetch adapter for browser and modern Node.js environments. ```typescript import { createAlova } from 'alova'; import fetchAdapter from 'alova/fetch'; const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: fetchAdapter() }); ``` -------------------------------- ### Head Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Creates a HEAD request to the specified URL with optional configuration. Returns a Method instance for the HEAD request. ```APIDOC ## Head ### Description Creates a HEAD request. ### Method HEAD ### Endpoint `/url` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response Returns a `Method` instance for the HEAD request. ``` -------------------------------- ### Configuration Reference Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Details all available configuration options for Alova instances and requests. ```APIDOC ## Configuration Reference ### `createAlova()` options #### Description Configuration options for creating an Alova instance, including `baseURL`, `requestAdapter`, `cacheFor`, etc. ### Cache configuration #### Description Options for configuring cache behavior: `L1Cache`, `L2Cache`, `cacheFor`, `cacheMode`. ### State management #### Description Configuration for state management, primarily through the `statesHook` option. ### Lifecycle hooks #### Description Options for defining lifecycle hooks such as `beforeRequest` and `responded`. ### Request sharing and snapshots #### Description Configuration related to request sharing and snapshotting. ### Global configuration #### Description Setting global configuration options using the `globalConfig()` function. ### Per-request configuration overrides #### Description How to override global or instance-level configurations on a per-request basis. ``` -------------------------------- ### Basic Request Flow with Progress Handling and Cache Check Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/method-class.md Demonstrates a complete request flow using AlovaJS, including creating an instance, defining a method, adding a download progress handler, sending the request, and checking cache status. ```typescript import { createAlova } from 'alova'; import fetchAdapter from 'alova/fetch'; const alovaInstance = createAlova({ baseURL: 'https://api.example.com', requestAdapter: fetchAdapter() }); // Create method instance const userMethod = alovaInstance.Get('/users/123'); // Add progress handler userMethod.onDownload(({ loaded, total }) => { console.log(`Progress: ${(loaded / total * 100).toFixed(2)}%`); }); // Execute request try { const user = await userMethod.send(); console.log('User:', user); console.log('From cache?', userMethod.fromCache); } catch (error) { console.error('Failed:', error); } // Force refresh const freshUser = await userMethod.send(true); ``` -------------------------------- ### Create Alova Instance with Axios Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Initialize Alova using the axios adapter, optionally providing a custom Axios instance with pre-configurations. ```typescript import { createAlova } from 'alova'; import axiosAdapter from '@alova/adapter-axios'; import axios from 'axios'; const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: axiosAdapter({ axiosInstance: axios.create({ timeout: 30000 }) }) }); ``` -------------------------------- ### Create an OPTIONS request method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Use this method to create a Method instance for an OPTIONS request. It accepts the URL and optional configuration. ```typescript Options( url: string, config?: AlovaMethodCreateConfig ): Method> ``` -------------------------------- ### Prefetch Related Data Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Prefetches data for methods that match a name and method, such as 'GET' requests named 'Dashboard'. Useful for improving perceived performance. ```typescript const relatedMethods = alova.snapshots.match({ name: /Dashboard/, method: 'GET' }, true); await Promise.all( relatedMethods.map(method => method.send(true)) ); ``` -------------------------------- ### Invalidate Related Methods Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Invalidates the cache for methods matching specific criteria, such as GET requests to '/items'. Useful for ensuring related data is refreshed. ```typescript const listMethods = alova.snapshots.match({ method: 'GET', url: /\/items/ }, true); await Promise.all( listMethods.map(method => invalidateCache(method)) ); ``` -------------------------------- ### Assign Name to Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Assigns a string or number name to an Alova method. This name can be used later to reference the method, for example, in state updates. ```typescript const method = alova.Get('/api/users'); method.setName('getUserList'); // Later, reference by name await updateState(matcher.name === 'getUserList', (data) => data); ``` -------------------------------- ### Implement a Full Custom HTTP Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md This snippet shows how to create a custom Alova request adapter using a hypothetical `MyHttpClient`. It demonstrates how to handle request methods, URLs, headers, data, and implement response handling, headers retrieval, progress callbacks, and abort functionality. ```typescript import { AlovaRequestAdapter } from 'alova'; // Adapter for custom HTTP client export function customHttpAdapter(): AlovaRequestAdapter { return (elements, method) => { const httpClient = new MyHttpClient(); let requestAbort: () => void; return { response: async () => { return new Promise((resolve, reject) => { const request = httpClient.request({ method: elements.type, url: elements.url, headers: elements.headers, body: elements.data, onProgress: (loaded, total) => { // Handle download progress } }); requestAbort = () => request.cancel(); request.on('success', (data) => resolve(data)); request.on('error', (error) => reject(error)); }); }, headers: async () => { return {}; // Return response headers }, onDownload: (handler) => { // Implement download progress if supported }, onUpload: (handler) => { // Implement upload progress if supported }, abort: () => { requestAbort?.(); } }; }; } // Usage const alova = createAlova({ requestAdapter: customHttpAdapter() }); ``` -------------------------------- ### Utilities Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Helper functions and utilities for state management, configuration, and method manipulation. ```APIDOC ## Utilities ### `updateState(method, state)` #### Description Updates the reactive state associated with a specific method. ### `globalConfig(config)` #### Description Sets global configuration options for Alova. ### `Method.generateKey()` #### Description Static method on the `Method` class to generate cache keys. ### `Method.setName(name)` #### Description Static method on the `Method` class to set a name for a method. ### `promiseStatesHook()` #### Description A hook to access and manage the states of promises. ### `MethodSnapshotContainer.match(criteria)` #### Description Finds methods within the snapshot container based on specified criteria. ``` -------------------------------- ### Close Auto Hit Cache Behavior Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Shows the 'close' autoHitCache behavior where the `hitSource` option is ignored, and no automatic cache invalidation occurs. ```typescript globalConfig({ autoHitCache: 'close' }); const method = alova.Post('/users', data, { hitSource: listMethod }); // hitSource is ignored, no auto-invalidation ``` -------------------------------- ### Create a HEAD request method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Use this method to create a Method instance for a HEAD request. It accepts the URL and optional configuration. ```typescript Head( url: string, config?: AlovaMethodCreateConfig ): Method> ``` -------------------------------- ### AlovaGlobalCacheAdapter Interface Source: https://github.com/alovajs/alova/blob/main/_autodocs/types.md Interface for cache storage adapters, defining methods for setting, getting, removing, and clearing cached data. Supports both synchronous and asynchronous operations. ```typescript interface AlovaGlobalCacheAdapter { set(key: string, value: any): void | Promise; get(key: string): T | undefined | Promise; remove(key: string): void | Promise; clear(): void | Promise; } ``` -------------------------------- ### Node.js Cache with File Storage Source: https://github.com/alovajs/alova/blob/main/_autodocs/configuration.md Configure Alova for Node.js environments using a file-based cache adapter. This requires installing and importing a specific adapter like '@alova/storage-file'. ```typescript import { createAlova } from 'alova'; import fileAdapter from '@alova/storage-file'; import nodeAdapter from 'alova/node'; const alova = createAlova({ baseURL: 'https://api.example.com', l2Cache: fileAdapter(), requestAdapter: nodeAdapter() }); ``` -------------------------------- ### Self Auto Hit Cache Behavior Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Illustrates the 'self' autoHitCache behavior where cache invalidation via `hitSource` only affects methods within the same Alova instance. ```typescript globalConfig({ autoHitCache: 'self' }); const alova = createAlova({ ... }); const listMethod = alova.Get('/users'); const createMethod = alova.Post('/users', data, { hitSource: listMethod }); // Only invalidates caches in the same Alova instance ``` -------------------------------- ### MethodType Union Type Source: https://github.com/alovajs/alova/blob/main/_autodocs/types.md Defines the HTTP method type, supporting standard methods like GET, POST, PUT, DELETE, etc., as well as custom string methods. ```typescript type MethodType = | 'GET' | 'get' | 'POST' | 'post' | 'PUT' | 'put' | 'DELETE' | 'delete' | 'PATCH' | 'patch' | 'OPTIONS' | 'options' | 'HEAD' | 'head' | string; ``` -------------------------------- ### Create Alova Instance for Server-Side Rendering (Nuxt/Next) Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md Sets up Alova for server-side rendering environments like Nuxt or Next.js, using a Node.js HTTP adapter. ```typescript import { createAlova } from 'alova'; import nodeAdapter from '@alova/adapter-http'; export const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: nodeAdapter() }); ``` -------------------------------- ### Match Methods by HTTP Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Filters method instances based on their HTTP method type (e.g., 'GET', 'POST'). Can match a single method type or an array of types. ```typescript // Get all GET requests const getMethods = alova.snapshots.match({ method: 'GET' }, true); ``` -------------------------------- ### Create Alova Instance with XHR Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Initialize Alova with the xhr adapter for making requests using XMLHttpRequest in the browser. ```typescript import { createAlova } from 'alova'; import xhrAdapter from '@alova/adapter-xhr'; const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: xhrAdapter() }); ``` -------------------------------- ### Module Augmentation for Custom Types Source: https://github.com/alovajs/alova/blob/main/_autodocs/types.md Example of how to extend Alova's custom types using module augmentation. This allows adding project-specific metadata like feature and importance. ```typescript declare module 'alova' { interface AlovaCustomTypes { meta: { feature: string; importance: 'critical' | 'normal' | 'low'; }; } } ``` -------------------------------- ### onDownload Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/method-class.md Binds a download progress handler. This function is called with `{ loaded, total }` during download and returns an unbind function to remove the handler. ```APIDOC ## onDownload ### Description Binds a download progress handler. The handler function is called with `{ loaded, total }` during download. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **progressHandler** (ProgressHandler) - Required - Function called with `{ loaded, total }` during download ### Returns - `() => void` - Unbind function to remove the handler. ### Usage ```typescript const method = alovaInstance.Get('/large-file'); const unbind = method.onDownload(({ loaded, total }) => { console.log(`Downloaded ${loaded}/${total} bytes`); }); await method.send(); // Later, unbind the handler unbind(); ``` ``` -------------------------------- ### Global Auto Hit Cache Behavior Example Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Demonstrates the 'global' autoHitCache behavior where a request in one Alova instance can invalidate a method's cache in another instance if `hitSource` is configured. ```typescript const alova1 = createAlova({ id: 'api1', ... }); const alova2 = createAlova({ id: 'api2', ... }); const method1 = alova1.Get('/users'); const method2 = alova2.Post('/users', data, { hitSource: method1 // Invalidates method1 in alova1 }); ``` -------------------------------- ### Update Related Data After Request Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md After a request completes, use updateState to refresh related data. For example, after creating a new user, update the user list to include the newly created user. ```typescript const createUserMethod = alovaInstance.Post('/api/users', userData); const listMethod = alovaInstance.Get('/api/users'); createUserMethod.then(async (newUser) => { await updateState(listMethod, (oldList) => [ ...oldList, newUser ]); }); ``` -------------------------------- ### Requesting Data with Cache Disabled Source: https://github.com/alovajs/alova/blob/main/examples/server/views/psc.html This snippet demonstrates how to make multiple GET requests to '/api/psc' with caching explicitly disabled for each request using `cacheFor: null`. It logs the response to the dashboard and includes a delay between requests. ```javascript const requestTimes = 10; on('#btnRequest', 'click', async () => { dashboard.innerHTML = ''; btnRequest.setAttribute('disabled', 'disabled'); try { for (let i = 0; i < requestTimes; i++) { const res = await alovaInstance.Get('/api/psc', { cacheFor: null }); const divEl = document.createElement('div'); divEl.innerHTML = JSON.stringify(res); dashboard.appendChild(divEl); await new Promise(resolve => setTimeout(resolve, 1000)); } } finally { btnRequest.removeAttribute('disabled'); } }); ``` -------------------------------- ### useFetcher Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/client-hooks.md useFetcher is a hook for fetching data. It allows for manual triggering of requests and provides state management for loading, data, and errors. The `updateState` option ensures that the hook's state is updated upon successful fetch. ```APIDOC ## useFetcher ### Description A hook for fetching data with manual request triggering and state management for loading, data, and errors. The `updateState` option ensures that the hook's state is updated upon successful fetch. ### Usage Example ```typescript import { useFetcher } from '@alova/client'; function PrefetchButtons() { const { fetch, loading, data, error } = useFetcher({ updateState: true }); const handlePrefetch = async (userId) => { const result = await fetch( alovaInstance.Get(`/api/users/${userId}`) ); console.log('Prefetched:', result); }; return (
{loading && 'Fetching...'} {data &&

Last fetch: {JSON.stringify(data)}

} {error &&

Error: {error.message}

}
); } ``` ``` -------------------------------- ### MethodSnapshotContainer.match(matcher, matchAll) Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/utilities.md Finds method instances from snapshot history based on specified criteria. It allows matching by name, method type, URL, and more, returning either a single match or all matching methods. ```APIDOC ## MethodSnapshotContainer.match Finds method instances from snapshot history matching specific criteria. ### Signature ```typescript match( matcher: MethodFilter, matchAll?: M ): M extends true ? Method[] : Method | undefined ``` ### Parameters ```typescript type MethodFilter = { name?: string | RegExp; method?: MethodType | MethodType[]; url?: string | RegExp; fromUrl?: string | RegExp; fromMethod?: MethodType | MethodType[]; }; ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | matcher | `MethodFilter` | Yes | — | Criteria to match methods | | matchAll | `boolean` | No | `true` | Return all matches or first match only | ### Matcher Properties | Property | Type | Description | |----------|------|-------------| | name | `string \| RegExp` | Match method name (exact or pattern) | | method | `MethodType \| MethodType[]` | Match HTTP method(s) | | url | `string \| RegExp` | Match full URL | | fromUrl | `string \| RegExp` | Match URL excluding query params | | fromMethod | `MethodType \| MethodType[]` | Original method types | ### Returns - If `matchAll` is `true`: Array of matched Method instances - If `matchAll` is `false`: Single Method instance or `undefined` ### Usage ```typescript const alova = createAlova({ ... }); // Get all GET requests const getMethods = alova.snapshots.match({ method: 'GET' }, true); // Get first method named 'getUsers' const userMethod = alova.snapshots.match({ name: 'getUsers' }, false); // Match URL pattern const apiMethods = alova.snapshots.match({ url: /\/api\// }, true); // Complex matching const methods = alova.snapshots.match({ method: ['GET', 'POST'], url: /\/users/, name: /list|get/i }, true); ``` ``` -------------------------------- ### External Store for Svelte HMR State Source: https://github.com/alovajs/alova/blob/main/examples/svelte/README.md Use an external store to preserve component state during Hot Module Replacement (HMR). This example demonstrates a simple writable store using Svelte's store API. ```javascript // store.js // An extremely simple external store import { writable } from 'svelte/store'; export default writable(0); ``` -------------------------------- ### Alova Class - Post Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Creates a POST request to a specified URL with optional request data and configuration. Returns a Method instance for the POST request. ```APIDOC ## Alova Class - Post Method ### Description Creates a POST request. ### Signature ```typescript Post( url: string, data?: RequestBody, config?: AlovaMethodCreateConfig ): Method> ``` ### Parameters #### url - **url** (`string`) - Required - The request URL #### data - **data** (`RequestBody`) - Optional - Request body (object, string, FormData, Blob, ArrayBuffer, URLSearchParams, or ReadableStream) #### config - **config** (`AlovaMethodCreateConfig`) - Optional - Optional configuration ### Return Type A `Method` instance for the POST request. ### Usage Example ```typescript const createUserMethod = alovaInstance.Post('/api/users', { name: 'Alice', email: 'alice@example.com' }, { headers: { 'Content-Type': 'application/json' } }); const result = await createUserMethod.send(); ``` ``` -------------------------------- ### Put Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Creates a PUT request to the specified URL with optional data and configuration. Returns a Method instance for the PUT request. ```APIDOC ## Put ### Description Creates a PUT request. ### Method PUT ### Endpoint `/url` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (RequestBody) - Optional - Request body - **config** (AlovaMethodCreateConfig) - Optional - Optional configuration ### Request Example ```typescript alovaInstance.Put('/api/users/123', { name: 'Bob' }); ``` ### Response Returns a `Method` instance for the PUT request. ``` -------------------------------- ### Create Alova Instance with Node.js HTTP Adapter Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/adapters.md Initialize Alova with the http adapter for making requests using Node.js's built-in http/https modules. ```typescript import { createAlova } from 'alova'; import httpAdapter from '@alova/adapter-http'; const alova = createAlova({ baseURL: 'https://api.example.com', requestAdapter: httpAdapter() }); ``` -------------------------------- ### Core API - createAlova and Alova Class Source: https://github.com/alovajs/alova/blob/main/_autodocs/README.md The main entry point for creating Alova instances and the Alova class itself, which provides instance methods for making HTTP requests. ```APIDOC ## Core API ### `createAlova()` #### Description Factory function to create a new Alova instance. ### `Alova` class #### Description Represents an Alova instance with methods for making HTTP requests. #### Methods - `Get(path, config)` - `Post(path, config)` - `Put(path, config)` - `Delete(path, config)` - `Patch(path, config)` - `Head(path, config)` - `Options(path, config)` - `Request(path, config)` #### Configuration Provides default configuration values and allows per-request overrides. ``` -------------------------------- ### Create POST Request Method Source: https://github.com/alovajs/alova/blob/main/_autodocs/api-reference/alova-class.md Use the `Post` method to create a POST request. This method accepts the URL, request body data, and optional configuration for headers, etc. ```typescript const createUserMethod = alovaInstance.Post('/api/users', { name: 'Alice', email: 'alice@example.com' }, { headers: { 'Content-Type': 'application/json' } }); const result = await createUserMethod.send(); ```