### HTTP Method Shortcuts Examples Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Provides examples of using shortcut methods like `get`, `post`, `put`, and `delete` for common HTTP operations, including passing parameters and data. ```typescript // GET 请求 const users = await httpRequest.get('/api/users'); const user = await httpRequest.get('/api/users/1', { params: { include: 'profile' } }); // POST 请求 const newUser = await httpRequest.post('/api/users', { name: 'John', email: 'john@example.com' }); // PUT 请求 const updatedUser = await httpRequest.put('/api/users/1', { name: 'John Doe' }); // DELETE 请求 await httpRequest.delete('/api/users/1'); ``` -------------------------------- ### Install @seed-fe/request and Axios Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Instructions for installing the @seed-fe/request library and its peer dependency, Axios, using npm, yarn, or pnpm. ```bash npm install @seed-fe/request axios ``` ```bash yarn add @seed-fe/request axios ``` ```bash pnpm add @seed-fe/request axios ``` -------------------------------- ### Basic HTTP Requests with httpRequest Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Shows how to perform basic GET and POST requests using the `httpRequest` object provided by the library after configuration. ```typescript import httpRequest from '@seed-fe/request'; // 发送 GET 请求 const data = await httpRequest.get('/api/users'); // 发送 POST 请求 const result = await httpRequest.post('/api/users', { name: 'John' }); ``` -------------------------------- ### Retrieve Full HTTP Response with Seed-fe-request Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md This example shows how to obtain the complete HTTP response object, including status code and headers, by setting the `withFullResponse` option to `true`. The response object contains `status`, `headers`, and `data` properties. ```typescript const response = await httpRequest.get('/api/users', { withFullResponse: true }); console.log(response.status); console.log(response.headers); console.log(response.data); ``` -------------------------------- ### Get Request Instance Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Explains how to retrieve a specific request instance by its name using `getRequestInstance`, allowing for targeted API calls. ```typescript import { getRequestInstance } from '@seed-fe/request'; const apiInstance = getRequestInstance('api1'); const data = await apiInstance.get('/users'); ``` -------------------------------- ### Seed-fe-request Type Definitions Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md This snippet provides type definitions for `InstanceName` and `RequestInstance`. `InstanceName` is defined as a string or symbol, while `RequestInstance` defines the methods available for making HTTP requests (get, post, put, delete, patch, head, options) with generic type support. ```typescript type InstanceName = string | symbol; interface RequestInstance { (config: CustomRequestConfig): Promise; get(url: string, config?: CustomRequestConfig): Promise; post(url: string, data?: unknown, config?: CustomRequestConfig): Promise; put(url: string, data?: unknown, config?: CustomRequestConfig): Promise; delete(url: string, config?: CustomRequestConfig): Promise; patch(url: string, data?: unknown, config?: CustomRequestConfig): Promise; head(url: string, config?: CustomRequestConfig): Promise; options(url: string, config?: CustomRequestConfig): Promise; } ``` -------------------------------- ### Normalize Errors with Seed-fe-request Interceptors Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md This example shows how to normalize errors thrown by request or response interceptors using the `normalizeError` function from `@seed-fe/request`. This ensures all errors are consistently formatted as `Promise.reject(Error)`. ```typescript import { normalizeError } from '@seed-fe/request'; const requestInterceptor = { onError: (error: unknown) => normalizeError(error) }; const responseInterceptor = { onError: (error: unknown) => normalizeError(error) }; ``` -------------------------------- ### Testing Basic HTTP Request Functionality Source: https://github.com/xianghongai/seed-fe-request/blob/main/TEST.md Tests the fundamental HTTP request capabilities, verifying the implementation of various HTTP methods like GET, POST, PUT, and DELETE. It also checks the handling of request configurations, including URL parameters, request bodies, and headers. ```TypeScript import axios from 'axios'; describe('Request Functionality', () => { it('should perform a GET request', async () => { const response = await axios.get('/data'); expect(response.status).toBe(200); expect(response.data).toBeDefined(); }); it('should perform a POST request with data', async () => { const postData = { key: 'value' }; const response = await axios.post('/submit', postData, { headers: { 'Content-Type': 'application/json' } }); expect(response.status).toBe(201); expect(response.data).toEqual(postData); }); it('should handle URL parameters', async () => { const response = await axios.get('/items', { params: { id: 123 } }); expect(response.config.url).toContain('?id=123'); }); }); ``` -------------------------------- ### Configure Multiple API Instances with Seed-fe-request Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md This snippet demonstrates how to configure multiple API instances by providing an array of configurations to `defineRequestConfig`. Each configuration includes an `instanceName`, `baseURL`, and `timeout`. It also shows how to use these different instances for making requests. ```typescript defineRequestConfig([ { instanceName: 'mainAPI', baseURL: 'https://api.example.com', timeout: 5000 }, { instanceName: 'authAPI', baseURL: 'https://auth.example.com', timeout: 3000 } ]); const users = await request({ url: '/users', instanceName: 'mainAPI' }); const authInfo = await request({ url: '/login', instanceName: 'authAPI' }); ``` -------------------------------- ### Define Request Instance Configurations Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Illustrates how to register request instance configurations using `defineRequestConfig`, supporting both single configurations and arrays of configurations for multiple instances. ```typescript // 单个配置 defineRequestConfig({ baseURL: 'https://api.example.com', timeout: 5000 }); // 多个配置 defineRequestConfig([ { instanceName: 'api1', baseURL: 'https://api1.example.com' }, { instanceName: 'api2', baseURL: 'https://api2.example.com' } ]); ``` -------------------------------- ### Interceptor Configuration - Function Format Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Shows how to configure interceptors using simple functions for both request and response handling. ```typescript interceptors: { request: (config) => { // 处理请求配置 return config; }, response: (response) => { // 处理响应数据 return response; } } ``` -------------------------------- ### Interceptor Configuration - Object Format Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Demonstrates configuring interceptors using an object format with `onConfig` and `onError` properties for more granular control. ```typescript interceptors: { request: { onConfig: (config) => config, onError: (error) => Promise.reject(error) }, response: { onConfig: (response) => response, onError: (error) => Promise.reject(error) } } ``` -------------------------------- ### Interceptor Configuration - Tuple Format Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Illustrates configuring interceptors using tuple (array) format, specifying fulfillment and rejection handlers. ```typescript interceptors: { request: [ (config) => config, // onFulfilled (error) => Promise.reject(error) // onRejected ], response: [ (response) => response, (error) => Promise.reject(error) ] } ``` -------------------------------- ### Testing Instance Creation and Management Source: https://github.com/xianghongai/seed-fe-request/blob/main/TEST.md Covers the functionality for creating and managing Axios instances, including default, named, and Symbol instances. It verifies instance configuration and isolation between instances, as well as the mechanisms for retrieving and managing these instances. ```TypeScript import axios, { AxiosInstance } from 'axios'; describe('Instance Management', () => { it('should create a default instance', () => { const instance = axios; expect(instance).toBeDefined(); }); it('should create named instances', () => { const instance1 = axios.create({ baseURL: 'https://api.example.com/v1' }); const instance2 = axios.create({ baseURL: 'https://api.example.com/v2' }); expect(instance1.defaults.baseURL).toBe('https://api.example.com/v1'); expect(instance2.defaults.baseURL).toBe('https://api.example.com/v2'); expect(instance1).not.toBe(instance2); }); it('should maintain instance isolation', async () => { const instanceA = axios.create({ timeout: 1000 }); const instanceB = axios.create({ timeout: 5000 }); expect(instanceA.defaults.timeout).toBe(1000); expect(instanceB.defaults.timeout).toBe(5000); }); it('should retrieve instances by key/symbol', () => { const key = Symbol('api'); const instance = axios.create({ baseURL: 'https://symbol.com' }); // Assuming a mechanism to register/retrieve instances by symbol // const retrievedInstance = getInstance(key); // expect(retrievedInstance.defaults.baseURL).toBe('https://symbol.com'); }); }); ``` -------------------------------- ### Configure Request Instance with Interceptors Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Demonstrates how to define default request configurations, including setting the base URL, timeout, and configuring request and response interceptors using the `defineRequestConfig` function. ```typescript import { defineRequestConfig } from '@seed-fe/request'; // 定义默认配置 defineRequestConfig({ baseURL: 'https://api.example.com', timeout: 5000, interceptors: { request: { onConfig: (config) => { config.headers.Authorization = `Bearer ${getToken()}`; return config; } }, response: { onConfig: (response) => response.data, // 默认已支持 onError: (error) => { console.error('请求失败:', error); return Promise.reject(error); } } } }); ``` -------------------------------- ### Mocking Axios for Testing Source: https://github.com/xianghongai/seed-fe-request/blob/main/TEST.md Provides mock functionality for the testing environment, including creating mock Axios instances, requests, and responses. It also defines helper functions for creating mock responses and errors, and offers functionality to reset mock states for test isolation. ```TypeScript import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; // Create a mock instance const mock = new MockAdapter(axios); // Mock a GET request mock.onGet('/users').reply(200, { users: [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Smith' } ] }); // Mock a POST request mock.onPost('/users', { name: 'New User' }).reply(201, { id: 3, name: 'New User' }); // Mock a response with an error mock.onGet('/error').reply(500, { message: 'Internal Server Error' }); // Helper to create a mock response const createMockResponse = (data: any, status: number = 200) => ({ data, status }); // Helper to create a mock error const createMockError = (message: string, status: number = 500) => ({ message, status }); // Reset mock state // mock.reset(); ``` -------------------------------- ### Global Request Method Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Details the global `request` function for making HTTP requests, which allows specifying the instance name to use for the request. ```typescript import { request } from '@seed-fe/request'; const data = await request({ url: '/api/users', method: 'GET', instanceName: 'api1' // 可选,指定使用的实例 }); ``` -------------------------------- ### Interceptor Configuration - Array Format (Multiple Interceptors) Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md Shows how to apply multiple interceptors in an array, supporting different formats (function, object, tuple) within the same list. ```typescript interceptors: { request: [ (config) => config, { onConfig: (config) => config, onError: (error) => Promise.reject(error) }, [ (config) => config, (error) => Promise.reject(error) ] ] } ``` -------------------------------- ### Testing Response Data Handling Source: https://github.com/xianghongai/seed-fe-request/blob/main/TEST.md Focuses on the logic for processing response data. It verifies the default behavior of extracting `response.data` and tests the `withFullResponse` option to control whether the complete response object or just the data is returned. It also checks the handling of various response data types. ```TypeScript import axios from 'axios'; describe('Response Handling', () => { it('should return response.data by default', async () => { // Assume a mock response with data: { message: 'Success' } const response = await axios.get('/simple'); expect(response).toEqual({ message: 'Success' }); }); it('should return the full response when withFullResponse is true', async () => { // Assume a mock response with data: { message: 'Full Response' } and status: 200 const response = await axios.get('/full', { params: { withFullResponse: true } }); expect(response.data).toEqual({ message: 'Full Response' }); expect(response.status).toBe(200); }); it('should handle array response data', async () => { // Assume a mock response with data: [1, 2, 3] const response = await axios.get('/array'); expect(Array.isArray(response)).toBe(true); expect(response).toEqual([1, 2, 3]); }); }); ``` -------------------------------- ### Verifying Module Exports Source: https://github.com/xianghongai/seed-fe-request/blob/main/TEST.md Ensures the completeness and correctness of module exports, confirming that all public APIs are correctly exported and accessible. It tests the consistency of default and named exports, as well as the correct export of constants and types. ```TypeScript import * as SeedFeRequest from '../src'; // Assuming the library is exported from src describe('Module Exports', () => { it('should export the default function correctly', () => { expect(SeedFeRequest.default).toBeInstanceOf(Function); }); it('should export named functions and types', () => { expect(SeedFeRequest.create).toBeInstanceOf(Function); expect(SeedFeRequest.ResponseType).toBeDefined(); // Example type export expect(SeedFeRequest.AxiosInstance).toBeDefined(); // Example type export }); it('should export constants correctly', () => { expect(SeedFeRequest.DEFAULT_TIMEOUT).toBeDefined(); // Example constant export }); it('should have consistent exports', () => { // Add checks to ensure named exports match expected functions/values expect(typeof SeedFeRequest.get).toBe('function'); expect(typeof SeedFeRequest.post).toBe('function'); }); }); ``` -------------------------------- ### Implement Custom Error Handling in Seed-fe-request Source: https://github.com/xianghongai/seed-fe-request/blob/main/README.md This snippet illustrates how to define custom error handling logic using the `errorConfig` and `errorHandler` options in `defineRequestConfig`. It shows how to handle specific errors, like a 401 Unauthorized error, by redirecting to a login page. It also demonstrates how to skip the error handler for specific requests using `skipErrorHandler`. ```typescript defineRequestConfig({ baseURL: 'https://api.example.com', errorConfig: { errorHandler: (error, { config }) => { if (error.response?.status === 401) { redirectToLogin(); } } } }); const data = await httpRequest.get('/api/users', { skipErrorHandler: true }); ``` -------------------------------- ### Testing Error Handling Mechanisms Source: https://github.com/xianghongai/seed-fe-request/blob/main/TEST.md Examines the error handling workflows and mechanisms. It verifies error capturing, propagation, and processing logic. The tests also cover the registration and execution of custom error handlers and the error throwing mechanisms. ```TypeScript import axios from 'axios'; describe('Error Handling', () => { it('should catch and handle request errors', async () => { // Assume a mock that returns a 404 error await expect(axios.get('/nonexistent')).rejects.toThrow(); }); it('should allow registering custom error handlers', async () => { const customErrorHandler = (error) => { return Promise.reject({ ...error, handled: true }); }; axios.interceptors.response.use(undefined, customErrorHandler); // Assume a mock that returns a 500 error await expect(axios.get('/server-error')).rejects.toHaveProperty('handled', true); }); it('should propagate errors correctly', async () => { // Assume a mock that throws an error await expect(axios.get('/throw')).rejects.toThrow('Specific Error Message'); }); }); ``` -------------------------------- ### Testing Interceptor Functionality Source: https://github.com/xianghongai/seed-fe-request/blob/main/TEST.md Tests the functionality of request and response interceptors, supporting various formats like functions, objects, tuples, and arrays. It verifies the execution order and scope of interceptors, as well as the addition, execution, and cleanup of one-time interceptors. ```TypeScript import axios from 'axios'; describe('Interceptors', () => { it('should support function interceptors', async () => { axios.interceptors.request.use((config) => { config.headers['X-Custom-Header'] = 'Function'; return config; }); // Assume a mock request is made await axios.get('/interceptor-test'); // Assert that the header was added }); it('should support object interceptors', async () => { axios.interceptors.response.use({ onFulfilled: (response) => { response.data.processed = true; return response; }, onRejected: (error) => { return Promise.reject(error); } }); // Assume a mock response is received const response = await axios.get('/response-interceptor'); expect(response.data.processed).toBe(true); }); it('should execute interceptors in order', async () => { let order = []; axios.interceptors.request.use((config) => { order.push(1); return config; }); axios.interceptors.request.use((config) => { order.push(2); return config; }); await axios.get('/order-test'); expect(order).toEqual([1, 2]); }); it('should handle one-time interceptors', async () => { const interceptor = axios.interceptors.request.use((config) => { config.headers['X-One-Time'] = 'true'; return config; }); await axios.get('/one-time'); axios.interceptors.request.eject(interceptor); // Make another request and assert the header is not present }); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.