File size: 1,613 Bytes
bbb1195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * HTTP API Client for Cloud Deployment
 * Replaces Tauri IPC with REST API calls
 */

export interface ApiResponse<T> {
    success: boolean;
    data?: T;
    error?: string;
}

/**
 * Base API request function
 */
async function apiRequest<T>(
    endpoint: string,
    options?: RequestInit
): Promise<T> {
    const response = await fetch(endpoint, {
        headers: {
            'Content-Type': 'application/json',
            ...options?.headers,
        },
        ...options,
    });

    if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || `HTTP ${response.status}`);
    }

    const result: ApiResponse<T> = await response.json();

    if (!result.success) {
        throw new Error(result.error || 'Unknown error');
    }

    return result.data as T;
}

/**
 * API client with convenience methods
 */
export const api = {
    /**
     * GET request
     */
    get: <T>(url: string): Promise<T> => apiRequest<T>(url),

    /**
     * POST request
     */
    post: <T>(url: string, body?: unknown): Promise<T> =>
        apiRequest<T>(url, {
            method: 'POST',
            body: body ? JSON.stringify(body) : undefined,
        }),

    /**
     * DELETE request
     */
    delete: <T>(url: string): Promise<T> =>
        apiRequest<T>(url, {
            method: 'DELETE',
        }),

    /**
     * PUT request
     */
    put: <T>(url: string, body?: unknown): Promise<T> =>
        apiRequest<T>(url, {
            method: 'PUT',
            body: body ? JSON.stringify(body) : undefined,
        }),
};

export default api;