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
46
47
48
49
50
51
52
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;
},
): 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,
},
});
const text = await resp.text();
if (!resp.ok) {
throw new Error(text);
}
if (!text) {
return null;
}
return JSON.parse(text);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
v17
April 10, 2024