summaryrefslogtreecommitdiff
path: root/api/client.ts
blob: 703b1f05513058f461096cbbd7244d45953c1102 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import Constants from "expo-constants";
import * as SecureStore from "expo-secure-store";

function getApiBaseUrl() {
  const envUrl = (process as any)?.env?.API_BASE_URL;
  const extraUrl =
    (Constants.manifest as any)?.extra?.API_BASE_URL ||
    (Constants.expoConfig as any)?.extra?.API_BASE_URL;
  if (envUrl) return envUrl;
  if (extraUrl) return extraUrl;

  throw new Error("API_BASE_URL is not defined in environment or Expo config");
}

const API_BASE_URL = getApiBaseUrl();

const AUTH_TOKEN_KEY = "buddy_auth_token";
const SELECTED_DEVICE_KEY = "buddy_selected_device";

class ApiClient {
  private token: string | null = null;
  private selectedDeviceId: string | null = null;

  async initialize() {
    try {
      this.token = await SecureStore.getItemAsync(AUTH_TOKEN_KEY);
      this.selectedDeviceId =
        await SecureStore.getItemAsync(SELECTED_DEVICE_KEY);
    } catch (e) {
      console.error("Failed to load auth token", e);
    }
  }

  async setToken(token: string) {
    this.token = token;
    await SecureStore.setItemAsync(AUTH_TOKEN_KEY, token);
  }

  async clearToken() {
    this.token = null;
    await SecureStore.deleteItemAsync(AUTH_TOKEN_KEY);
  }

  async setSelectedDevice(deviceId: string) {
    this.selectedDeviceId = deviceId;
    await SecureStore.setItemAsync(SELECTED_DEVICE_KEY, deviceId);
  }

  getSelectedDeviceId(): string | null {
    return this.selectedDeviceId;
  }

  isAuthenticated(): boolean {
    return this.token !== null;
  }

  private async request<T>(
    method: "GET" | "POST" | "PUT" | "DELETE",
    endpoint: string,
    body?: any,
  ): Promise<T> {
    const headers: HeadersInit = {
      "Content-Type": "application/json",
    };

    if (this.token) {
      headers["Authorization"] = `Bearer ${this.token}`;
    }

    const response = await fetch(`${API_BASE_URL}${endpoint}`, {
      method,
      headers,
      body: body ? JSON.stringify(body) : undefined,
    });

    if (!response.ok) {
      const error = await response
        .json()
        .catch(() => ({ reason: "Unknown error" }));
      throw new Error(error.reason || `HTTP ${response.status}`);
    }

    return response.json();
  }

  async get<T>(endpoint: string): Promise<T> {
    return this.request<T>("GET", endpoint);
  }

  async post<T>(endpoint: string, body?: any): Promise<T> {
    return this.request<T>("POST", endpoint, body);
  }

  async delete<T>(endpoint: string, body?: any): Promise<T> {
    return this.request<T>("DELETE", endpoint, body);
  }

  // Auth endpoints
  async signIn(
    email: string,
    password: string,
  ): Promise<{ success: boolean; token?: string; reason?: string }> {
    const result = await this.post<{
      success: boolean;
      token: string;
      reason: string;
    }>("/signin", {
      email,
      password,
    });

    if (result.success && result.token) {
      await this.setToken(result.token);
    }

    return result;
  }

  async signUp(
    email: string,
    password: string,
  ): Promise<{ success: boolean; token?: string; reason?: string }> {
    const result = await this.post<{
      success: boolean;
      token: string;
      reason: string;
    }>("/signup", {
      email,
      password,
    });

    if (result.success && result.token) {
      await this.setToken(result.token);
    }

    return result;
  }

  async signOut() {
    await this.clearToken();
  }
}

export const apiClient = new ApiClient();

// Initialize on import
apiClient.initialize();