Files
gen2d/frontend/src/api/client.ts
T

67 lines
1.4 KiB
TypeScript
Raw Normal View History

import type { ApiResponse } from './types'
const TOKEN_KEY = 'gen2d_token'
export function getToken(): string | null {
return localStorage.getItem(TOKEN_KEY)
}
export function setToken(token: string): void {
localStorage.setItem(TOKEN_KEY, token)
}
export function clearToken(): void {
localStorage.removeItem(TOKEN_KEY)
}
export class ApiError extends Error {
code: number
constructor(code: number, message: string) {
super(message)
this.code = code
}
}
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const token = getToken()
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(options.headers as Record<string, string>),
}
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
const res = await fetch(url, {
...options,
headers,
credentials: 'include',
})
const json: ApiResponse<T> = await res.json()
if (json.code !== 0) {
throw new ApiError(json.code, json.message)
}
return json.data
}
export function get<T>(url: string): Promise<T> {
return request<T>(url)
}
export function post<T>(url: string, body?: unknown): Promise<T> {
return request<T>(url, {
method: 'POST',
body: body ? JSON.stringify(body) : undefined,
})
}
export function put<T>(url: string, body?: unknown): Promise<T> {
return request<T>(url, {
method: 'PUT',
body: body ? JSON.stringify(body) : undefined,
})
}