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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
|
import { hc } from "hono/client";
import type { AppType } from "../../server/index.js";
import type { ApiError, AuthResponse, Tokens } from "./types";
export class ApiClientError extends Error {
constructor(
message: string,
public status: number,
public code?: string,
) {
super(message);
this.name = "ApiClientError";
}
}
export interface TokenStorage {
getTokens(): Tokens | null;
setTokens(tokens: Tokens): void;
clearTokens(): void;
}
const TOKEN_STORAGE_KEY = "kioku_tokens";
export const localStorageTokenStorage: TokenStorage = {
getTokens(): Tokens | null {
const stored = localStorage.getItem(TOKEN_STORAGE_KEY);
if (!stored) return null;
try {
return JSON.parse(stored) as Tokens;
} catch {
return null;
}
},
setTokens(tokens: Tokens): void {
localStorage.setItem(TOKEN_STORAGE_KEY, JSON.stringify(tokens));
},
clearTokens(): void {
localStorage.removeItem(TOKEN_STORAGE_KEY);
},
};
export interface ApiClientOptions {
baseUrl?: string;
tokenStorage?: TokenStorage;
}
// RPC client type - use this for type-safe API calls
export type Client = ReturnType<typeof hc<AppType>>;
export function createClient(baseUrl: string): Client {
return hc<AppType>(baseUrl);
}
export class ApiClient {
private tokenStorage: TokenStorage;
private refreshPromise: Promise<boolean> | null = null;
public readonly rpc: Client;
constructor(options: ApiClientOptions = {}) {
const baseUrl = options.baseUrl ?? window.location.origin;
this.tokenStorage = options.tokenStorage ?? localStorageTokenStorage;
this.rpc = createClient(baseUrl);
}
private async handleResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
const errorBody = (await response.json().catch(() => ({}))) as ApiError;
throw new ApiClientError(
errorBody.error || `Request failed with status ${response.status}`,
response.status,
errorBody.code,
);
}
if (response.status === 204) {
return undefined as T;
}
return response.json() as Promise<T>;
}
private async refreshToken(): Promise<boolean> {
if (this.refreshPromise) {
return this.refreshPromise;
}
this.refreshPromise = this.doRefreshToken();
try {
return await this.refreshPromise;
} finally {
this.refreshPromise = null;
}
}
private async doRefreshToken(): Promise<boolean> {
const tokens = this.tokenStorage.getTokens();
if (!tokens?.refreshToken) {
return false;
}
try {
const res = await this.rpc.api.auth.refresh.$post({
json: { refreshToken: tokens.refreshToken },
});
if (!res.ok) {
return false;
}
const data = await res.json();
this.tokenStorage.setTokens({
accessToken: data.accessToken,
refreshToken: data.refreshToken,
});
return true;
} catch {
return false;
}
}
async register(username: string, password: string) {
const res = await this.rpc.api.auth.register.$post({
json: { username, password },
});
return this.handleResponse<{ user: { id: string; username: string } }>(res);
}
async login(username: string, password: string): Promise<AuthResponse> {
const res = await this.rpc.api.auth.login.$post({
json: { username, password },
});
const data = await this.handleResponse<AuthResponse>(res);
this.tokenStorage.setTokens({
accessToken: data.accessToken,
refreshToken: data.refreshToken,
});
return data;
}
logout(): void {
this.tokenStorage.clearTokens();
}
isAuthenticated(): boolean {
return this.tokenStorage.getTokens() !== null;
}
getTokens(): Tokens | null {
return this.tokenStorage.getTokens();
}
getAuthHeader(): { Authorization: string } | undefined {
const tokens = this.tokenStorage.getTokens();
if (tokens?.accessToken) {
return { Authorization: `Bearer ${tokens.accessToken}` };
}
return undefined;
}
}
export const apiClient = new ApiClient();
|