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
Imports:
Constants like
Authorizationfor header keys.Types such as ResponseType for API response typing.
Localization module
i18nfor internationalized messages.Utility functions from authorization and common utilities.
UI components (
message,notification) from Ant Design for user feedback.umi-requestfor HTTP request extension and method typing.
FAILED_TO_FETCH: A constant string used to detect network failures.RetcodeMessage: A dictionary mapping HTTP status codes to localized user-friendly messages.ResultCode: A TypeScript union type representing the supported HTTP status codes.
Functions and Methods
errorHandler
const errorHandler = (error: { response: Response; message: string }): Response
Purpose: Handles errors during HTTP requests globally.
Parameters:
error: An object containing the rawresponseand errormessage.
Returns: The
Responseobject if available; otherwise, a fallback object with a custom error code.Behavior:
If the error message matches a network failure (
Failed to fetch), it triggers a network anomaly notification.For other errors with an HTTP response, it shows an error notification with the status code and URL.
Usage: Passed as the global error handler to
umi-request's extendedrequest.
request
const request: RequestMethod = extend({ errorHandler, timeout: 300000, getResponse: true });
Purpose: A customized HTTP request method extending
umi-requestwith default timeout, error handling, and options to get the full response.Properties:
errorHandler: Custom error handler defined above.timeout: Request timeout set to 300,000 ms (5 minutes).getResponse: Ensures the full response object is returned, not just the body.
Request Interceptor
request.interceptors.request.use((url: string, options: any) => {...});
Purpose: Intercepts all outgoing requests to modify options before sending.
Behavior:
Converts all keys in
dataandparamsfrom camelCase to snake_case usingconvertTheKeysOfTheObjectToSnake.Conditionally adds authorization headers unless
skipTokenis set in options.Preserves any explicitly set headers.
Enables
interceptorsflag in options.
Parameters:
url: The request URL.options: Request options including headers, data, params, etc.
Returns: Modified request parameters and options.
Response Interceptor
request.interceptors.response.use(async (response: Response, options) => {...});
Purpose: Intercepts responses to handle specific HTTP codes and application-level codes.
Behavior:
Displays error messages for HTTP 413 (Payload Too Large) and 504 (Gateway Timeout).
For
blobresponse types, returns the raw response.Parses JSON body to check application-specific codes:
code === 100: Shows an error message.code === 401: Notifies the user, clears authorization, redirects to login.Other non-zero codes: Shows a notification with the error code and message.
Parameters:
response: The raw HTTP response.options: Request options, including theresponseType.
Returns: The original response object.
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);
Purpose: Performs an HTTP GET request.
Parameters:
url- The endpoint URL as a string.Returns: A promise resolving with the response.
post
export const post = (url: string, body: any) => request.post(url, { data: body });
Purpose: Performs an HTTP POST request.
Parameters:
url: The endpoint URL as a string.body: The request payload.
Returns: A promise resolving with the response.
drop and put
export const drop = () => {};
export const put = () => {};
Purpose: Placeholder functions likely intended for future implementation of DELETE and PUT requests.
Note: Currently empty and non-functional.
Implementation Details and Algorithms
Key Transformation: Before sending requests, all keys in
dataandparamsare converted from camelCase to snake_case using a utility function. This design supports back-end APIs expecting snake_case keys, improving consistency and reducing manual transformation.Error Handling: Uses both HTTP status codes and application-specific response codes (
codein JSON) to determine the appropriate user notification or action (e.g., redirect to login on 401).Authorization Management: Automatically adds an authorization token header to requests unless explicitly skipped, centralizing auth logic.
Response Cloning: The response body is cloned before JSON parsing to allow multiple reads if needed.
Timeout: Requests are set to timeout after 5 minutes, balancing responsiveness and long-running processes.
Interaction with Other Parts of the System
Authorization Utilities: Relies on
authorizationUtilfor retrieving and removing authorization tokens andredirectToLoginfor user redirection.Localization (
i18n): Fetches localized messages for network errors, HTTP status codes, and other notifications to support internationalization.UI Feedback: Uses Ant Design components (
message,notification) to provide consistent and user-friendly feedback for network and API errors.Common Utilities: Uses
convertTheKeysOfTheObjectToSnakefromcommon-utilto ensure API compatibility regarding key naming conventions.Umi-request: Extends and customizes the third-party
umi-requestlibrary to fit the application's requirements.
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:
The
Requestclass represents the extendedumi-requestinstance.It contains the
errorHandlerfunction and exposes HTTP methods likegetandpost.It uses two interceptors:
requestinterceptor that modifies outgoing requests.responseinterceptor that processes incoming responses.
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.