8058
Ir
irvc / files
irvc / web / src / lib / api.ts
1.1 KB
1export async function api<T>(path: string, init?: RequestInit): Promise<T> { 2 const res = await fetch(`/api${path}`, { 3 credentials: "same-origin", 4 headers: { "Content-Type": "application/json" }, 5 ...init, 6 }); 7 if (!res.ok) { 8 const body = await res.json().catch(() => ({ error: res.statusText })); 9 throw new Error(body.error ?? "request failed"); 10 } 11 if (res.status === 204) return undefined as T; 12 return res.json() as Promise<T>; 13} 14 15export async function gifs(query: string): Promise<{ url: string; preview: string }[]> { 16 const { gifs } = await api<{ gifs: { url: string; preview: string }[] }>( 17 `/gifs?q=${encodeURIComponent(query)}`, 18 ); 19 return gifs; 20} 21 22export async function upload(file: File): Promise<{ url: string }> { 23 const form = new FormData(); 24 form.append("file", file); 25 const res = await fetch("/api/upload", { 26 method: "POST", 27 credentials: "same-origin", 28 body: form, 29 }); 30 if (!res.ok) { 31 const body = await res.json().catch(() => ({ error: res.statusText })); 32 throw new Error(body.error ?? "upload failed"); 33 } 34 return res.json(); 35}