Files
Teamup/client/src/lib/api.ts
T

32 lines
1.0 KiB
TypeScript
Raw Normal View History

import { useAuth } from '../store/auth'
async function request<T>(method: string, url: string, body?: unknown): Promise<T> {
const token = useAuth.getState().token
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
})
if (response.status === 401) {
useAuth.getState().logout()
}
if (!response.ok) {
const text = await response.text()
throw new Error(`${response.status} ${response.statusText}${text ? `: ${text}` : ''}`)
}
const contentType = response.headers.get('content-type') ?? ''
return contentType.includes('application/json') ? ((await response.json()) as T) : (undefined as T)
}
export const api = {
get: <T>(url: string) => request<T>('GET', url),
post: <T>(url: string, body?: unknown) => request<T>('POST', url, body),
patch: <T>(url: string, body?: unknown) => request<T>('PATCH', url, body),
}