feat(frontend): 步骤 6.4 — API 客户端封装

This commit is contained in:
hhs
2026-06-10 15:24:16 +08:00
parent 3041ce770f
commit 5e3da508cf

62
frontend/src/api/agent.ts Normal file
View File

@@ -0,0 +1,62 @@
import { API_CONFIG } from "@/config/api-config";
import {
Response,
AiAgentConfigResponseDTO,
CreateSessionResponseDTO,
ChatRequestDTO,
ChatResponseDTO,
} from "@/types/api";
const handleResponse = async <T>(
response: globalThis.Response
): Promise<Response<T>> => {
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
if (data.code !== "0000") {
throw new Error(data.info || "Unknown API error");
}
return data;
};
export const agentApi = {
/**
* 查询已注册的 AI Agent 列表
* GET /api/v1/query_ai_agent_config_list
*/
queryAgentList: async (): Promise<Response<AiAgentConfigResponseDTO[]>> => {
const resp = await fetch(`${API_CONFIG.BASE_URL}/query_ai_agent_config_list`);
return handleResponse<AiAgentConfigResponseDTO[]>(resp);
},
/**
* 创建聊天会话
* POST /api/v1/create_session
*/
createSession: async (
agentId: string,
userId: string
): Promise<Response<CreateSessionResponseDTO>> => {
const resp = await fetch(`${API_CONFIG.BASE_URL}/create_session`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ agentId, userId }),
});
return handleResponse<CreateSessionResponseDTO>(resp);
},
/**
* 发送聊天消息
* POST /api/v1/chat
*/
chat: async (data: ChatRequestDTO): Promise<Response<ChatResponseDTO>> => {
const resp = await fetch(`${API_CONFIG.BASE_URL}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
return handleResponse<ChatResponseDTO>(resp);
},
};