Spaces:
Runtime error
Runtime error
export class Client { | |
private baseUrl: string; | |
private token: string; | |
constructor(baseUrl: string, token: string) { | |
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl; | |
this.token = token; | |
} | |
private getHeaders(contentType?: string): HeadersInit { | |
const headers: HeadersInit = { | |
Authorization: `Bearer ${this.token}`, | |
}; | |
if (contentType) { | |
headers["Content-Type"] = contentType; | |
} | |
return headers; | |
} | |
private async handleResponse<T>(response: Response): Promise<T> { | |
if (!response.ok) { | |
throw new Error(`API request failed: ${response.statusText}`); | |
} | |
return response.json(); | |
} | |
async get<T>(path: string): Promise<T> { | |
const url = `${this.baseUrl}${path.startsWith("/") ? path : "/" + path}`; | |
const response = await fetch(url, { | |
headers: this.getHeaders(), | |
}); | |
return this.handleResponse<T>(response); | |
} | |
async post<T>(path: string, payload: unknown): Promise<T> { | |
const url = `${this.baseUrl}${path.startsWith("/") ? path : "/" + path}`; | |
const response = await fetch(url, { | |
method: "POST", | |
headers: this.getHeaders("application/json"), | |
body: JSON.stringify(payload), | |
}); | |
return this.handleResponse<T>(response); | |
} | |
} | |