File size: 1,910 Bytes
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
 * Backend API Hook - REST API calls to WidgetTDC Backend
 */

import { API_URL } from '../config/api';

interface APIResponse<T = unknown> {
  success: boolean;
  data?: T;
  error?: string;
}

export const useBackendAPI = () => {
  const fetchAPI = async <T = unknown>(
    endpoint: string,
    options?: RequestInit
  ): Promise<APIResponse<T>> => {
    try {
      const response = await fetch(`${API_URL}${endpoint}`, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...options?.headers,
        },
      });

      const data = await response.json();

      if (!response.ok) {
        return { success: false, error: data.error || 'Request failed' };
      }

      return { success: true, data };
    } catch (error) {
      return { success: false, error: (error as Error).message };
    }
  };

  // Health check
  const getHealth = () => fetchAPI('/health');

  // MCP Tool execution via REST
  const callMCPTool = async (tool: string, params?: Record<string, unknown>) => {
    return fetchAPI('/api/mcp/route', {
      method: 'POST',
      body: JSON.stringify({ tool, params }),
    });
  };

  // Knowledge API
  const searchKnowledge = (query: string) =>
    fetchAPI(`/api/knowledge/search?q=${encodeURIComponent(query)}`);

  // Memory API
  const getMemoryEntities = (orgId: string, userId?: string) =>
    fetchAPI(`/api/memory/entities?orgId=${orgId}${userId ? `&userId=${userId}` : ''}`);

  // Notes API
  const getNotes = (userId: string, orgId: string) =>
    fetchAPI(`/api/notes?userId=${userId}&orgId=${orgId}`);

  // System Info
  const getSystemInfo = () => fetchAPI('/api/sys');

  // Logs
  const getLogs = () => fetchAPI('/api/logs');

  return {
    fetchAPI,
    getHealth,
    callMCPTool,
    searchKnowledge,
    getMemoryEntities,
    getNotes,
    getSystemInfo,
    getLogs,
  };
};

export default useBackendAPI;