Spaces:
Sleeping
Sleeping
File size: 1,640 Bytes
a4e3218 0e7a159 d8db673 a4e3218 d8db673 0e7a159 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import type { Meta, SuggestHit, TreeQuery, TreeResponse, DefinitionPayload } from "./types";
async function json<T>(res: Response): Promise<T> {
if (!res.ok) {
const text = await res.text();
throw new Error(text || res.statusText);
}
return res.json() as Promise<T>;
}
export const api = {
meta: () => fetch("/api/meta").then((r) => json<Meta>(r)),
suggest: (q: string) =>
fetch(`/api/suggest?q=${encodeURIComponent(q)}&limit=18`).then((r) => json<{ hits: SuggestHit[] }>(r)),
tree: (body: TreeQuery, signal?: AbortSignal) =>
fetch("/api/tree", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal,
}).then((r) => json<TreeResponse>(r)),
node: (term: string, lang: string) =>
fetch(`/api/node?term=${encodeURIComponent(term)}&lang=${encodeURIComponent(lang)}`).then((r) => json<Record<string, unknown>>(r)),
define: (term: string, lang: string, iso?: string | null) => {
const params = new URLSearchParams({ term, lang });
if (iso) params.set("iso", iso);
return fetch(`/api/define?${params}`).then((r) => json<DefinitionPayload>(r));
},
exportUrl: (body: TreeQuery) => {
return fetch("/api/export?format=csv", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}).then(async (r) => {
const blob = await r.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "reverse-etymology.csv";
a.click();
URL.revokeObjectURL(url);
});
},
};
|