register-server.ts
Overview
The register-server.ts file provides utility functions to dynamically generate API request service objects based on given configuration mappings. These services abstract HTTP request details, allowing developers to invoke API endpoints with simple method calls while managing request URLs, methods, and parameters internally.
Two main exports are present:
registerServer- Creates a service object based on a mapping of endpoint configurations and a generic request method fromumi-request.registerNextServer- Creates a service object tailored for Axios-based requests, supporting dynamic URL generation and flexible request configuration.
These utilities promote consistency and reduce boilerplate in API request handling across a TypeScript project.
Detailed Explanation
Types and Constants
Service<T extends string>
A generic type defining a service object whose keys are strings T mapped to functions. Each function optionally accepts:
params?: any- parameters for the request, typically query params or request body.urlAppendix?: string- additional URL path appended to base URL.
Returns any (usually a promise resolving to response data).
type Service<T extends string> = Record<
T,
(params?: any, urlAppendix?: string) => any
>;
Methods
An array of HTTP methods (post, delete, put) that require the request body to be sent in the data field.
const Methods = ['post', 'delete', 'put'];
Function: registerServer
function registerServer<T extends string>(
opt: Record<T, { url: string; method: string }>,
request: RequestMethod,
): Service<T>
Purpose
Creates a service object where each key corresponds to an API endpoint defined in opt. Each method calls the provided request function with appropriate URL, HTTP method, and parameters.
Parameters
opt: A record where each key is an endpoint name with an object specifying:url: The base URL string for the endpoint.method: The HTTP method string (get,post,put,delete, etc.).
request: A request function compatible with the interface ofumi-request'sRequestMethod.
Returns
An object (
server) of typeService<T>, where each key is a function that performs the HTTP request to the configured endpoint.
Implementation Details
Iterates over each key in
opt.For each key:
Constructs the URL; appends
urlAppendixif provided.If the method is one of
post,delete, orput, it sends parameters in thedatafield.If the method is
get, it sends parameters as query params.
Uses lodash's
omitto excludemethodandurlproperties from additional request options.
Usage Example
import request from 'umi-request';
const apiConfig = {
getUser: { url: '/api/user', method: 'get' },
createUser: { url: '/api/user', method: 'post' },
};
const api = registerServer(apiConfig, request);
// Call a GET endpoint with query params
api.getUser({ id: 123 }).then(response => console.log(response));
// Call a POST endpoint with request body
api.createUser({ name: 'Alice' }).then(response => console.log(response));
Function: registerNextServer
function registerNextServer<T extends string>(
requestRecord: Record<
T,
{ url: string | ((...args: any[]) => string); method: string }
>
): Record<
T,
(
config?: AxiosRequestConfig<any> | Record<string, any> | string | number | boolean | undefined,
useAxiosNativeConfig?: boolean,
) => Promise<AxiosResponse<any, any>>
>
Purpose
Creates a service object tailored for requests using Axios (or a compatible wrapper). Supports dynamic URL generation by allowing the URL to be a function that computes the URL from the request config.
Parameters
requestRecord: A record mapping endpoint names to an object with:url: Either a string URL or a function returning a URL string.method: HTTP method string (get,post, etc.).
Returns
An object where each key is a function returning a
Promiseof Axios response. Each function accepts:config- Request configuration or data, could be:Axios request config object,
Simple data types (string, number, boolean),
Or a plain object of parameters.
useAxiosNativeConfig(optional) - Boolean flag indicating whether to passconfigdirectly to Axios (true), or wrap it inside{ data: config }(false, default).
Implementation Details
Iterates over each entry in
requestRecord.For each endpoint:
Computes the final URL either by calling the URL function or using the URL string.
Constructs the Axios request config:
If
useAxiosNativeConfigis true, usesconfigas is.Otherwise, wraps
configinside{ data: config }.Ensures
finalConfigis an object.
Invokes the Axios
requestfunction imported from'./next-request'with combined config.
Usage Example
const requestRecord = {
fetchPosts: {
url: (params) => `/posts/${params.userId}`,
method: 'get',
},
createPost: {
url: '/posts',
method: 'post',
},
};
const server = registerNextServer(requestRecord);
// Dynamic URL with params
server.fetchPosts({ userId: 42 }).then(res => console.log(res.data));
// Post request with data
server.createPost({ title: 'Hello' }).then(res => console.log(res.data));
Important Implementation Details and Algorithms
Dynamic URL Handling:
registerNextServersupports URL strings or functions, enabling dynamic URL construction based on input parameters.Method Differentiation:
registerServerdistinguishes between HTTP methods that send data in the request body (post,put,delete) and those that send query parameters (get).Flexible Config Support:
registerNextServerallows passing either raw Axios configs or simple data objects, controlled by theuseAxiosNativeConfigflag.Safe Property Access: Uses
Object.prototype.hasOwnPropertyto avoid prototype pollution issues when iterating keys.Use of Lodash Utilities:
omitis used to clean configuration objects from unwanted keys before passing them to the request function.
Interaction with Other Parts of the System
Imports a custom
requestfunction from'./next-request', which presumably wraps Axios or another HTTP client.Designed to work with the
umi-requestlibrary'sRequestMethodinterface for theregisterServerfunction.Provides a standardized way to generate API services that can be used throughout the application for consistent HTTP communication.
Likely integrated in a larger API layer or service layer of a frontend or Node.js backend application.
Mermaid Class Diagram
classDiagram
class registerServer {
+<T>(opt: Record<T, {url: string; method: string}>, request: RequestMethod): Service<T>
}
class registerNextServer {
+<T>(requestRecord: Record<T, {url: string | function; method: string}>): Server<T>
}
class Service~T~ {
+[key: T](params?: any, urlAppendix?: string): any
}
class Server~T~ {
+[key: T](config?: AxiosRequestConfig | object | string | number | boolean, useAxiosNativeConfig?: boolean): Promise<AxiosResponse>
}
registerServer ..> Service : returns
registerNextServer ..> Server : returns
class Methods {
<<constant>>
+post
+delete
+put
}
Summary
The register-server.ts file simplifies API service creation by providing two flexible factory functions: one for generic request functions (e.g., umi-request) and one tailored for Axios-based requests with dynamic URLs. It abstracts away HTTP methods, URL construction, and parameter placement, enabling clean, maintainable API client code across projects.