| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- // API client for SmartBotic CRM backend
- const API_BASE = '/api'
- interface RequestOptions {
- method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
- body?: unknown
- headers?: Record<string, string>
- }
- class ApiClient {
- private accessToken: string | null = null
- setAccessToken(token: string | null) {
- this.accessToken = token
- }
- getAccessToken(): string | null {
- return this.accessToken
- }
- async request<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
- const { method = 'GET', body, headers = {} } = options
- const requestHeaders: Record<string, string> = {
- 'Content-Type': 'application/json',
- ...headers,
- }
- if (this.accessToken) {
- requestHeaders['Authorization'] = `Bearer ${this.accessToken}`
- }
- const response = await fetch(`${API_BASE}${endpoint}`, {
- method,
- headers: requestHeaders,
- body: body ? JSON.stringify(body) : undefined,
- })
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({ error: 'Unknown error' }))
- throw new Error(errorData.error || `HTTP ${response.status}`)
- }
- return response.json()
- }
- // Convenience methods
- get<T>(endpoint: string, headers?: Record<string, string>): Promise<T> {
- return this.request<T>(endpoint, { method: 'GET', headers })
- }
- post<T>(endpoint: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
- return this.request<T>(endpoint, { method: 'POST', body, headers })
- }
- patch<T>(endpoint: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
- return this.request<T>(endpoint, { method: 'PATCH', body, headers })
- }
- delete<T>(endpoint: string, headers?: Record<string, string>): Promise<T> {
- return this.request<T>(endpoint, { method: 'DELETE', headers })
- }
- }
- export const apiClient = new ApiClient()
- export default apiClient
|