| 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}`), |
| }; |
|
|