- 添加环境变量支持,可通过 NEXT_PUBLIC_API_BASE_URL 配置后端地址 - 实现智能地址获取:无配置时自动使用当前域名+3006端口 - 添加 .env.template 模板文件,方便部署时配置 - 更新 package.json 脚本支持通过 PORT 环境变量配置前端端口 - 修改 .gitignore 允许模板文件提交但保护敏感环境文件 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
88 lines
2.5 KiB
TypeScript
88 lines
2.5 KiB
TypeScript
import {
|
|
ApiResponse,
|
|
ListAccountsBody,
|
|
ListAccountsResponse,
|
|
BatchDeleteBody,
|
|
BatchUpdateBody,
|
|
StatsOverview,
|
|
ScriptUploadItem
|
|
} from './types';
|
|
|
|
const getApiBaseUrl = () => {
|
|
// 检查是否有配置的环境变量(构建时注入)
|
|
const envUrl = process.env.NEXT_PUBLIC_API_BASE_URL;
|
|
if (envUrl && envUrl !== 'undefined') {
|
|
return envUrl;
|
|
}
|
|
|
|
// 在浏览器环境中,没有配置则使用当前域名
|
|
if (typeof window !== 'undefined') {
|
|
return `${window.location.protocol}//${window.location.hostname}:3006`;
|
|
}
|
|
|
|
// 服务端渲染时的默认值
|
|
return 'http://localhost:3006';
|
|
};
|
|
|
|
class ApiClient {
|
|
private async request<T>(
|
|
endpoint: string,
|
|
options: RequestInit = {}
|
|
): Promise<ApiResponse<T>> {
|
|
const API_BASE_URL = getApiBaseUrl(); // 每次请求时动态获取
|
|
const url = `${API_BASE_URL}${endpoint}`;
|
|
|
|
const response = await fetch(url, {
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...options.headers,
|
|
},
|
|
...options,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
// 获取账户列表
|
|
async getAccountsList(body: ListAccountsBody): Promise<ApiResponse<ListAccountsResponse>> {
|
|
return this.request<ListAccountsResponse>('/web/v1/accounts/list', {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
// 批量删除账户
|
|
async batchDeleteAccounts(body: BatchDeleteBody): Promise<ApiResponse<{ deletedCount: number }>> {
|
|
return this.request<{ deletedCount: number }>('/web/v1/accounts/delete-batch', {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
// 批量更新账户
|
|
async batchUpdateAccounts(body: BatchUpdateBody): Promise<ApiResponse<{ updatedCount: number }>> {
|
|
return this.request<{ updatedCount: number }>('/web/v1/accounts/update-batch', {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
// 获取统计概览
|
|
async getStatsOverview(): Promise<ApiResponse<StatsOverview>> {
|
|
return this.request<StatsOverview>('/web/v1/stats/overview');
|
|
}
|
|
|
|
// 上传账户
|
|
async uploadAccounts(accounts: ScriptUploadItem[], ownerId: string): Promise<ApiResponse<{ processedCount: number; createdCount: number; updatedCount: number }>> {
|
|
return this.request<{ processedCount: number; createdCount: number; updatedCount: number }>(`/s/v1/${ownerId}/upload`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(accounts),
|
|
});
|
|
}
|
|
}
|
|
|
|
export const apiClient = new ApiClient(); |