Files
knowledge-graph-agent/frontend/src/services/graphApi.ts
T

82 lines
2.1 KiB
TypeScript
Raw Normal View History

2026-04-05 14:41:11 +08:00
import axios from 'axios';
import type { GraphData, Node, Edge } from '../types/graph';
2026-04-06 14:24:45 +08:00
import { API_BASE_URL, API_TIMEOUT } from '../config/constants';
2026-04-05 14:41:11 +08:00
2026-04-06 14:24:45 +08:00
/**
* API 客户端实例
* 统一配置了 base URL、超时时间和默认请求头
*/
2026-04-05 14:41:11 +08:00
const apiClient = axios.create({
baseURL: API_BASE_URL,
2026-04-06 14:24:45 +08:00
timeout: API_TIMEOUT,
2026-04-05 14:41:11 +08:00
headers: {
'Content-Type': 'application/json',
},
});
2026-04-06 14:24:45 +08:00
/**
* 知识图谱 API 服务
* 提供与后端交互的所有图谱相关接口
*/
2026-04-05 14:41:11 +08:00
export const graphApi = {
2026-04-06 14:24:45 +08:00
/**
* 获取完整的知识图谱数据
* @returns 节点和边的集合
*/
2026-04-05 14:41:11 +08:00
async getData(): Promise<GraphData> {
try {
const response = await apiClient.get<GraphData>('/graph');
return response.data;
} catch (error) {
2026-04-06 14:24:45 +08:00
console.error('Failed to fetch graph data:', error);
2026-04-05 14:41:11 +08:00
return { nodes: [], edges: [] };
}
},
2026-04-06 14:24:45 +08:00
/**
* 搜索节点(后端搜索)
* @param query 搜索关键词
* @returns 匹配的节点列表
*/
2026-04-05 14:41:11 +08:00
async searchNodes(query: string): Promise<Node[]> {
try {
const response = await apiClient.get<Node[]>(`/search?q=${encodeURIComponent(query)}`);
return response.data;
} catch (error) {
2026-04-06 14:24:45 +08:00
console.error('Failed to search nodes:', error);
2026-04-05 14:41:11 +08:00
return [];
}
},
2026-04-06 14:24:45 +08:00
/**
* 根据 ID 获取节点详情
* @param id 节点 ID
* @returns 节点对象或 null
*/
2026-04-05 14:41:11 +08:00
async getNodeById(id: string): Promise<Node | null> {
try {
const response = await apiClient.get<Node>(`/nodes/${id}`);
return response.data;
} catch (error) {
2026-04-06 14:24:45 +08:00
console.error('Failed to fetch node:', error);
2026-04-05 14:41:11 +08:00
return null;
}
},
2026-04-06 14:24:45 +08:00
/**
* 获取节点的邻居节点和连接边
* @param nodeId 节点 ID
* @returns 包含邻居节点和边的对象
*/
2026-04-05 14:41:11 +08:00
async getNeighbors(nodeId: string): Promise<{ nodes: Node[]; edges: Edge[] }> {
try {
const response = await apiClient.get(`/nodes/${nodeId}/neighbors`);
return response.data;
} catch (error) {
2026-04-06 14:24:45 +08:00
console.error('Failed to fetch neighbors:', error);
2026-04-05 14:41:11 +08:00
return { nodes: [], edges: [] };
}
},
};
export default apiClient;