Public
Script
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
import { API_URL } from "https://esm.town/v/std/API_URL";
export async function fetchAPI(
path: string,
options?: RequestInit & {
paginate?: boolean;
token?: string;
},
): Promise<Response> {
const auth = options?.token ? `Bearer ${options.token}` : 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, {
headers: {
...options?.headers,
Authorization: auth,
},
});
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 new Response(JSON.stringify({ data }), {
headers: {
"Content-Type": "application/json",
},
});
}
return fetch(`${API_URL}${path}`, {
...options,
headers: {
...options?.headers,
Authorization: auth,
},
});
}
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!
June 17, 2024