summaryrefslogtreecommitdiff
path: root/lib/api-utils.ts
diff options
context:
space:
mode:
Diffstat (limited to 'lib/api-utils.ts')
-rw-r--r--lib/api-utils.ts45
1 files changed, 45 insertions, 0 deletions
diff --git a/lib/api-utils.ts b/lib/api-utils.ts
new file mode 100644
index 00000000..fa954cac
--- /dev/null
+++ b/lib/api-utils.ts
@@ -0,0 +1,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()
+ }
+ }
+ \ No newline at end of file