client.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // API client for SmartBotic CRM backend
  2. const API_BASE = '/api'
  3. interface RequestOptions {
  4. method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
  5. body?: unknown
  6. headers?: Record<string, string>
  7. }
  8. class ApiClient {
  9. private accessToken: string | null = null
  10. setAccessToken(token: string | null) {
  11. this.accessToken = token
  12. }
  13. getAccessToken(): string | null {
  14. return this.accessToken
  15. }
  16. async request<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
  17. const { method = 'GET', body, headers = {} } = options
  18. const requestHeaders: Record<string, string> = {
  19. 'Content-Type': 'application/json',
  20. ...headers,
  21. }
  22. if (this.accessToken) {
  23. requestHeaders['Authorization'] = `Bearer ${this.accessToken}`
  24. }
  25. const response = await fetch(`${API_BASE}${endpoint}`, {
  26. method,
  27. headers: requestHeaders,
  28. body: body ? JSON.stringify(body) : undefined,
  29. })
  30. if (!response.ok) {
  31. const errorData = await response.json().catch(() => ({ error: 'Unknown error' }))
  32. throw new Error(errorData.error || `HTTP ${response.status}`)
  33. }
  34. return response.json()
  35. }
  36. // Convenience methods
  37. get<T>(endpoint: string, headers?: Record<string, string>): Promise<T> {
  38. return this.request<T>(endpoint, { method: 'GET', headers })
  39. }
  40. post<T>(endpoint: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
  41. return this.request<T>(endpoint, { method: 'POST', body, headers })
  42. }
  43. patch<T>(endpoint: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
  44. return this.request<T>(endpoint, { method: 'PATCH', body, headers })
  45. }
  46. delete<T>(endpoint: string, headers?: Record<string, string>): Promise<T> {
  47. return this.request<T>(endpoint, { method: 'DELETE', headers })
  48. }
  49. }
  50. export const apiClient = new ApiClient()
  51. export default apiClient