import { API_URL } from "https://esm.town/v/std/API_URL";
export async function api<T = any>(
path: string,
options?: RequestInit & {
authenticated?: boolean;
paginate?: boolean;
parseResponse?: boolean;
},
): Promise<T> {
const authorization = options?.authenticated ? `Bearer ${Deno.env.get("valtown")}` : undefined;
if (options?.paginate) {
const data = [];
let url = new URL(`${API_URL}${path}`);
url.searchParams.set("limit", "100");
while (true) {
const resp = await fetch(url);
if (!resp.ok) {
throw new Error(await resp.text());
}
const res = await resp.json();
data.push(...res.data);
if (!res.links.next) {
break;
}
url = new URL(res.links.next);
}
return { data } as T;
}
const resp = await fetch(`${API_URL}${path}`, {
...options,
headers: {
...options?.headers,
Authorization: authorization,
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const contentType = resp.headers.get("content-type");
if (options?.parseResponse === false || !contentType?.includes("application/json")) {
return resp.arrayBuffer() as unknown as T;
}
const text = await resp.text();
if (!text) {
return null;
}
try {
return JSON.parse(text);
} catch (e) {
console.warn("Failed to parse response as JSON, returning raw text");
return text as unknown as T;
}
}