HF_catalyst / frontend /api /apiClient.ts
SissiFeng's picture
Initial commit
cdb8847
import { Workflow, RunResult, ApiResponse, HealthStatus } from '../types/types';
// 默认超时时间(毫秒)
const DEFAULT_TIMEOUT = 30000;
// 后端API基础URL
const API_BASE_URL = '/api'; // 如果是代理模式,前缀为/api
/**
* 带超时的fetch请求
*/
async function fetchWithTimeout(
url: string,
options: RequestInit = {},
timeout = DEFAULT_TIMEOUT
): Promise<Response> {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
}
/**
* 统一处理API响应
*/
async function handleResponse<T>(response: Response): Promise<ApiResponse<T>> {
try {
const data = await response.json();
if (!response.ok) {
return {
success: false,
error: data.error || `请求失败: ${response.status}`,
status_code: response.status
};
}
return {
success: true,
data,
status_code: response.status
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : '未知错误',
status_code: response.status
};
}
}
/**
* API客户端
*/
const apiClient = {
/**
* 运行实验工作流
*/
runExperiment: async (workflow: Workflow): Promise<ApiResponse<RunResult>> => {
try {
const response = await fetchWithTimeout(
`${API_BASE_URL}/run_experiment`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(workflow),
}
);
return handleResponse<RunResult>(response);
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : '未知错误',
};
}
},
/**
* 检查后端健康状态
*/
checkHealth: async (): Promise<ApiResponse<HealthStatus>> => {
try {
const startTime = Date.now();
const response = await fetchWithTimeout(
`${API_BASE_URL}/health`,
{
method: 'GET',
},
5000 // 健康检查使用较短的超时时间
);
const latency = Date.now() - startTime;
const result = await handleResponse<any>(response);
if (result.success) {
return {
success: true,
data: {
status: 'online',
message: 'Lab服务器在线',
latency
},
status_code: result.status_code
};
} else {
return {
success: true,
data: {
status: 'offline',
message: result.error || 'Lab服务器异常',
latency
},
status_code: result.status_code
};
}
} catch (error) {
return {
success: false,
data: {
status: 'offline',
message: error instanceof Error ? error.message : '连接失败'
},
error: error instanceof Error ? error.message : '未知错误',
};
}
},
/**
* 获取工作流执行状态
*/
getRunStatus: async (runId: string): Promise<ApiResponse<RunResult>> => {
try {
const response = await fetchWithTimeout(
`${API_BASE_URL}/run_status/${runId}`,
{
method: 'GET',
}
);
return handleResponse<RunResult>(response);
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : '未知错误',
};
}
},
};
export default apiClient;