blob: fa954cace5a8346066577b3d7e807866aff821b2 (
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
|
export class ApiClient {
private static baseUrl = '/api'
static async get(endpoint: string, params?: Record<string, string | number>) {
const url = new URL(`${this.baseUrl}${endpoint}`, window.location.origin)
if (params) {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, String(value))
})
}
const response = await fetch(url.toString())
if (!response.ok) {
const error = new Error(`API Error: ${response.status}`)
;(error as any).status = response.status
;(error as any).url = url.toString()
throw error
}
return response.json()
}
static async post(endpoint: string, data: any) {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
const error = new Error(errorData.message || `API Error: ${response.status}`)
;(error as any).status = response.status
;(error as any).url = `${this.baseUrl}${endpoint}`
throw error
}
return response.json()
}
}
|