client.ts 2.18 KB
import { ApiResponse, ApiError, isSuccessCode } from './types';

export interface ApiClientOptions {
  baseUrl?: string;
}

export interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  headers?: Record<string, string>;
  body?: unknown;
}

const DEFAULT_BASE_URL = '/api/v1';

export function createApiClient(options: ApiClientOptions = {}) {
  const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;

  async function request<T>(
    endpoint: string,
    requestOptions: RequestOptions = {}
  ): Promise<T> {
    const { method = 'GET', headers = {}, body } = requestOptions;

    const url = `${baseUrl}${endpoint}`;
    const fetchOptions: RequestInit = {
      method,
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
    };

    if (body !== undefined && method !== 'GET') {
      fetchOptions.body = JSON.stringify(body);
    }

    try {
      const response = await fetch(url, fetchOptions);

      const json = (await response.json()) as ApiResponse<T>;

      if (!response.ok) {
        throw new ApiError(
          response.status,
          json.message || `HTTP Error: ${response.status}`,
          false
        );
      }

      if (!isSuccessCode(json.code)) {
        throw new ApiError(json.code, json.message, false);
      }

      return json.data;
    } catch (error) {
      if (ApiError.isApiError(error)) {
        throw error;
      }

      // Network error
      if (error instanceof TypeError) {
        throw new ApiError(0, '网络连接失败', true);
      }

      throw new ApiError(0, (error as Error).message || '未知错误', false);
    }
  }

  return {
    get: <T>(endpoint: string, options?: RequestOptions) =>
      request<T>(endpoint, { ...options, method: 'GET' }),
    post: <T>(endpoint: string, body: unknown, options?: RequestOptions) =>
      request<T>(endpoint, { ...options, method: 'POST', body }),
    put: <T>(endpoint: string, body: unknown, options?: RequestOptions) =>
      request<T>(endpoint, { ...options, method: 'PUT', body }),
    delete: <T>(endpoint: string, options?: RequestOptions) =>
      request<T>(endpoint, { ...options, method: 'DELETE' }),
  };
}

// Export types
export * from './types';