From dc4ceabc7beb515207b0b7cde15b94176f8e94cb Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Sat, 14 Feb 2026 00:16:14 +0800 Subject: [PATCH] refactor(api): centralize url normalization --- src/services/api/client.ts | 24 ++---------------------- src/services/api/models.ts | 16 +++------------- 2 files changed, 5 insertions(+), 35 deletions(-) diff --git a/src/services/api/client.ts b/src/services/api/client.ts index 38f89ab..e4921c7 100644 --- a/src/services/api/client.ts +++ b/src/services/api/client.ts @@ -7,10 +7,10 @@ import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import type { ApiClientConfig, ApiError } from '@/types'; import { BUILD_DATE_HEADER_KEYS, - MANAGEMENT_API_PREFIX, REQUEST_TIMEOUT_MS, VERSION_HEADER_KEYS } from '@/utils/constants'; +import { computeApiUrl } from '@/utils/connection'; class ApiClient { private instance: AxiosInstance; @@ -32,7 +32,7 @@ class ApiClient { * 设置 API 配置 */ setConfig(config: ApiClientConfig): void { - this.apiBase = this.normalizeApiBase(config.apiBase); + this.apiBase = computeApiUrl(config.apiBase); this.managementKey = config.managementKey; if (config.timeout) { @@ -42,26 +42,6 @@ class ApiClient { } } - /** - * 规范化 API Base URL - */ - private normalizeApiBase(base: string): string { - let normalized = base.trim(); - - // 移除尾部的 /v0/management - normalized = normalized.replace(/\/?v0\/management\/?$/i, ''); - - // 移除尾部斜杠 - normalized = normalized.replace(/\/+$/, ''); - - // 添加协议 - if (!/^https?:\/\//i.test(normalized)) { - normalized = `http://${normalized}`; - } - - return `${normalized}${MANAGEMENT_API_PREFIX}`; - } - private readHeader( headers: Record | undefined, keys: string[] diff --git a/src/services/api/models.ts b/src/services/api/models.ts index 7441af0..1d687ed 100644 --- a/src/services/api/models.ts +++ b/src/services/api/models.ts @@ -4,27 +4,17 @@ import axios from 'axios'; import { normalizeModelList } from '@/utils/models'; +import { normalizeApiBase } from '@/utils/connection'; import { apiCallApi, getApiCallErrorMessage } from './apiCall'; -const normalizeBaseUrl = (baseUrl: string): string => { - let normalized = String(baseUrl || '').trim(); - if (!normalized) return ''; - normalized = normalized.replace(/\/?v0\/management\/?$/i, ''); - normalized = normalized.replace(/\/+$/g, ''); - if (!/^https?:\/\//i.test(normalized)) { - normalized = `http://${normalized}`; - } - return normalized; -}; - const buildModelsEndpoint = (baseUrl: string): string => { - const normalized = normalizeBaseUrl(baseUrl); + const normalized = normalizeApiBase(baseUrl); if (!normalized) return ''; return `${normalized}/models`; }; const buildV1ModelsEndpoint = (baseUrl: string): string => { - const normalized = normalizeBaseUrl(baseUrl); + const normalized = normalizeApiBase(baseUrl); if (!normalized) return ''; return `${normalized}/v1/models`; };