diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index e999345..ad2e4af 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -1,3 +1,5 @@ +import { getToken, removeToken } from './auth'; + const API_URL = process.env.NEXT_PUBLIC_API_URL || ''; class ApiClient { @@ -7,6 +9,31 @@ class ApiClient { this.baseUrl = baseUrl; } + private getHeaders(): Record { + const headers: Record = { + 'Content-Type': 'application/json', + }; + const token = typeof window !== 'undefined' ? getToken() : null; + if (token) { + headers['Authorization'] = `Bearer ${token}`; + } + return headers; + } + + private async handleResponse(response: Response): Promise { + if (response.status === 401) { + removeToken(); + if (typeof window !== 'undefined') { + window.location.href = '/login'; + } + throw new Error('Unauthorized'); + } + if (!response.ok) { + throw new Error(`API error: ${response.status}`); + } + return response.json(); + } + async get(path: string, params?: Record): Promise { const url = new URL(path, this.baseUrl || window.location.origin); if (params) { @@ -16,71 +43,37 @@ class ApiClient { } }); } - - const response = await fetch(url.toString(), { - headers: { - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - throw new Error(`API error: ${response.status}`); - } - - return response.json(); + const response = await fetch(url.toString(), { headers: this.getHeaders() }); + return this.handleResponse(response); } async post(path: string, data: any): Promise { const url = new URL(path, this.baseUrl || window.location.origin); - const response = await fetch(url.toString(), { method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, + headers: this.getHeaders(), body: JSON.stringify(data), }); - - if (!response.ok) { - throw new Error(`API error: ${response.status}`); - } - - return response.json(); + return this.handleResponse(response); } async put(path: string, data?: any): Promise { const url = new URL(path, this.baseUrl || window.location.origin); - const response = await fetch(url.toString(), { method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, + headers: this.getHeaders(), body: data ? JSON.stringify(data) : undefined, }); - - if (!response.ok) { - throw new Error(`API error: ${response.status}`); - } - - return response.json(); + return this.handleResponse(response); } async delete(path: string): Promise { const url = new URL(path, this.baseUrl || window.location.origin); - const response = await fetch(url.toString(), { method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - }, + headers: this.getHeaders(), }); - - if (!response.ok) { - throw new Error(`API error: ${response.status}`); - } - - return response.json(); + return this.handleResponse(response); } }