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:

  1. registerServer - Creates a service object based on a mapping of endpoint configurations and a generic request method from umi-request.

  2. 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:

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

Returns

Implementation Details

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

Returns

Implementation Details

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


Interaction with Other Parts of the System


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.