next-request.ts
Overview
The next-request.ts file serves as a centralized HTTP client utility for making API requests in the application. It uses the popular Axios library to create and configure an HTTP client instance that handles:
Automatic conversion of request data keys from camelCase to snake_case.
Injection of authorization headers (tokens) into outgoing requests.
Global response handling, including error notifications and handling specific response codes.
Providing simplified
getandpostwrapper functions for making HTTP requests.
This utility abstracts away repetitive request logic and provides consistent error handling and localization support, making it easier to interact with backend APIs throughout the application.
Detailed Explanations
Constants and Types
FAILED_TO_FETCH
Type:
stringValue:
'Failed to fetch'Purpose: A constant string used for matching network error messages to trigger specific UI notifications.
RetcodeMessage
Type:
{ [code in ResultCode]: string }Description: An object mapping HTTP result codes to localized user-friendly messages using the
i18ntranslation module.Usage: Used to display meaningful error or success messages based on HTTP status codes or response codes.
ResultCode
Type: Union type of specific HTTP status codes:
200 | 201 | 202 | 204 | 400 | 401 | 403 | 404 | 406 | 410 | 413 | 422 | 500 | 502 | 503 | 504Purpose: To restrict the codes considered in
RetcodeMessageand response handling to known HTTP statuses.
Functions
errorHandler
const errorHandler = (error: { response: Response; message: string; }): Response
Parameters:
error: An object containing:response: The HTTP response object from Axios.message: The error message string.
Returns: The
Responseobject if available; otherwise, a default object with{ data: { code: 1999 } }.Description:
Handles HTTP errors globally by:Checking if the error message matches
FAILED_TO_FETCHto detect network issues and show a localized notification.Otherwise, uses the HTTP status code from the response to display an appropriate error notification with status, URL, and localized message.
Example Usage:
try { const res = await request.get('/some-url'); } catch (error) { errorHandler(error); }
Axios Instance: request
const request = axios.create({
timeout: 300000,
});
Configuration:
Sets a request timeout of 300,000 ms (5 minutes).
Commented out options like
errorHandlerandgetResponsesuggest previous or potential configurations.
Interceptors:
Request Interceptor
Converts request data and query params keys from camelCase to snake_case using
convertTheKeysOfTheObjectToSnake.Injects the
Authorizationheader with a token retrieved viagetAuthorization()unlessskipTokenis set in the config.Returns the modified config object.
Response Interceptor
Handles specific HTTP status codes (413, 504) by showing error messages.
For
blobresponse types, returns the response directly.For JSON responses, inspects the response data's
codefield:100: Shows an error message.401: Shows an error notification, clears authorization data, and redirects to login.Any non-zero code (excluding 100 and 401): Shows a notification with the code and message.
In case of errors, logs the error, invokes
errorHandler, and rejects the promise.
Exported Utility Functions
get
export const get = (url: string) => request.get(url);
Parameters:
url: The URL string to send a GET request to.
Returns: A promise resolving to the Axios response.
Usage:
get('/api/users').then(response => { console.log(response.data); });
post
export const post = (url: string, body: any) => request.post(url, { data: body });
Parameters:
url: The URL string to send a POST request to.body: The payload/data to send in the POST request.
Returns: A promise resolving to the Axios response.
Usage:
post('/api/users', { name: 'John Doe' }).then(response => { console.log(response.data); });
drop and put
Declared but empty functions.
Presumably placeholders for future implementation of HTTP DELETE and PUT methods.
Important Implementation Details
Key Conversion: The utility converts request payload and query parameter keys from camelCase to snake_case to comply with backend API expectations. This conversion is done on every request automatically.
Authorization Handling: The token is dynamically added to request headers unless explicitly skipped. This promotes security and session management.
Error Handling and Localization: The file integrates with the i18n system to provide localized messages for users based on HTTP status codes and custom response codes.
Response Code Logic: Specific business logic is embedded in the response interceptor, particularly handling:
code === 100: Display error message.code === 401: Unauthorized, triggers logout and redirect.code !== 0: General error notification.
Blob Response Exception: If the response is a blob (e.g., file download), the response is returned as-is to avoid interfering with binary data.
Interaction with Other Parts of the Application
Localization (
i18n): Fetches localized messages for notifications and errors.Authorization Utilities: Imports functions to get authorization token, remove tokens, and redirect unauthenticated users.
UI Components: Uses
antdnotification and a custommessagecomponent for user feedback.Common Utilities: Uses a utility to convert object keys to snake_case format.
Axios: Core HTTP client library handling requests and responses.
This file is a foundational utility likely imported by various service or API modules across the application to perform HTTP requests consistently.
Visual Diagram
flowchart TD
A[Request Function Call] --> B[request Interceptors]
B --> |Request Interceptor| C[convert keys to snake_case]
C --> D{skipToken?}
D -- No --> E[Add Authorization Header]
D -- Yes --> E
E --> F[Send HTTP Request]
F --> G[Response Interceptor]
G --> H{Response Status}
H -- 413/504 --> I[Show error message]
H -- Other --> J{Response Type}
J -- blob --> K[Return response directly]
J -- json --> L{Response Data Code}
L -- 100 --> M[Show error message]
L -- 401 --> N[Show notification, logout, redirect]
L -- other non-zero --> O[Show notification]
L -- 0 --> P[Return response]
G -- Error --> Q[Call errorHandler, reject]
Summary
The next-request.ts file is a robust HTTP client abstraction built on Axios designed to facilitate API communication in the application. It focuses on:
Localization-aware error and status messaging.
Authorization token management.
Consistent payload key formatting.
Centralized and standardized error handling.
Simplified API method wrappers (
getandpost).
This utility promotes maintainable, clean, and secure network communication across the application.