request.ts


Overview

The request.ts file provides a centralized, enhanced HTTP request utility based on the umi-request library. It standardizes API request handling across the application by managing authorization headers, error handling, request/response interceptors, and response code messaging. This file simplifies making HTTP calls with consistent behavior, such as automatic key transformation (camelCase to snake_case), user notifications on errors, and redirecting unauthorized users to login.


Detailed Explanation

Imports and Constants


Functions and Methods

errorHandler

const errorHandler = (error: { response: Response; message: string }): Response

request

const request: RequestMethod = extend({ errorHandler, timeout: 300000, getResponse: true });

Request Interceptor

request.interceptors.request.use((url: string, options: any) => {...});

Response Interceptor

request.interceptors.response.use(async (response: Response, options) => {...});

Exported Convenience Methods

These wrapper methods simplify HTTP GET and POST usage by internally calling the extended request instance.

get

export const get = (url: string) => request.get(url);

post

export const post = (url: string, body: any) => request.post(url, { data: body });

drop and put

export const drop = () => {};
export const put = () => {};

Implementation Details and Algorithms


Interaction with Other Parts of the System


Usage Examples

import request, { get, post } from '@/utils/request';

// Simple GET request
get('/api/user/profile').then(response => {
  // handle response
});

// POST request with a payload
post('/api/user/update', { firstName: 'John', lastName: 'Doe' }).then(response => {
  // handle response
});

Mermaid Diagram

classDiagram
    class Request {
        -errorHandler(error)
        +interceptors
        +get(url)
        +post(url, body)
        +drop()
        +put()
    }

    class Interceptors {
        +request(url, options)
        +response(response, options)
    }

    Request --> Interceptors

Diagram Explanation:


Summary

The request.ts file is a crucial utility module that standardizes HTTP communication for the application. By centralizing error handling, authorization, key transformation, and localization, it promotes maintainable and consistent API interaction. Its integration with UI components enhances user experience by providing timely and meaningful feedback on network and API issues. The use of umi-request as a base ensures flexibility and extensibility for future enhancements.