refactor(api): centralize url normalization

This commit is contained in:
Supra4E8C
2026-02-14 00:16:14 +08:00
parent e13d7f5e0f
commit dc4ceabc7b
2 changed files with 5 additions and 35 deletions

View File

@@ -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<string, unknown> | undefined,
keys: string[]

View File

@@ -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`;
};