39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
// Базовый fetch к Go API
|
|
export function useApi() {
|
|
async function get<T>(path: string, params?: Record<string, string | number>) {
|
|
const url = new URL('/api' + path, window.location.origin)
|
|
if (params) {
|
|
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, String(v)))
|
|
}
|
|
const res = await fetch(url.toString())
|
|
if (!res.ok) throw new Error(await res.text())
|
|
return res.json() as Promise<T>
|
|
}
|
|
|
|
async function post<T>(path: string, body?: unknown) {
|
|
const res = await fetch('/api' + path, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
})
|
|
if (!res.ok) throw new Error(await res.text())
|
|
return res.json() as Promise<T>
|
|
}
|
|
|
|
async function del(path: string) {
|
|
const res = await fetch('/api' + path, { method: 'DELETE' })
|
|
if (!res.ok) throw new Error(await res.text())
|
|
return res.json()
|
|
}
|
|
|
|
async function upload(path: string, file: File) {
|
|
const form = new FormData()
|
|
form.append('file', file)
|
|
const res = await fetch('/api' + path, { method: 'POST', body: form })
|
|
if (!res.ok) throw new Error(await res.text())
|
|
return res.json()
|
|
}
|
|
|
|
return { get, post, del, upload }
|
|
}
|