File size: 2,020 Bytes
8f9c4ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useAuthStore } from '../stores/authStore';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';

class ApiClient {
  private baseUrl: string;
  constructor(baseUrl: string) { this.baseUrl = baseUrl; }

  private getAuthHeader(): Record<string, string> {
    const tokens = useAuthStore.getState().tokens;
    return tokens?.accessToken ? { Authorization: `Bearer ${tokens.accessToken}` } : {};
  }

  async request<T>(endpoint: string, config: { method?: string; body?: any } = {}): Promise<T> {
    const { method = 'GET', body } = config;
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      method,
      headers: { 'Content-Type': 'application/json', ...this.getAuthHeader() },
      body: body ? JSON.stringify(body) : undefined,
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.error?.message || 'Request failed');
    return data.data as T;
  }

  get<T>(e: string) { return this.request<T>(e); }
  post<T>(e: string, b?: any) { return this.request<T>(e, { method: 'POST', body: b }); }
  patch<T>(e: string, b?: any) { return this.request<T>(e, { method: 'PATCH', body: b }); }
  delete<T>(e: string) { return this.request<T>(e, { method: 'DELETE' }); }
}

export const api = new ApiClient(API_URL);

export const authApi = {
  register: (data: any) => api.post('/api/auth/register', data),
  login: (data: any) => api.post('/api/auth/login', data),
  me: () => api.get('/api/auth/me'),
};

export const roomsApi = {
  list: () => api.get('/api/rooms'),
  create: (data: any) => api.post('/api/rooms', data),
  get: (id: string) => api.get(`/api/rooms/${id}`),
  join: (inviteCode: string) => api.post('/api/rooms/join', { inviteCode }),
};

export const aiApi = {
  action: (data: any) => api.post('/api/ai/action', data),
};

export const snippetsApi = {
  list: () => api.get('/api/snippets'),
  create: (data: any) => api.post('/api/snippets', data),
  delete: (id: string) => api.delete(`/api/snippets/${id}`),
};