29 lines
686 B
TypeScript
29 lines
686 B
TypeScript
import { API_URL } from '@shared/config/env'
|
|
import { getCsrfToken } from './csrf'
|
|
|
|
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
|
const token = await getCsrfToken()
|
|
|
|
const res = await fetch(`${API_URL}${path}`, {
|
|
...options,
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-Token': token,
|
|
...options.headers,
|
|
},
|
|
})
|
|
|
|
const data = await res.json()
|
|
|
|
if (!res.ok) throw data
|
|
|
|
return data as T
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(path: string) => request<T>(path),
|
|
post: <T>(path: string, body: unknown) =>
|
|
request<T>(path, { method: 'POST', body: JSON.stringify(body) }),
|
|
}
|