0

Fetch records from a table

by
Published Apr 8, 2025
Script grist Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Grist = {
3
  apiKey: string;
4
  host: string;
5
};
6
/**
7
 * Fetch records from a table
8
 *
9
 */
10
export async function main(
11
  auth: Grist,
12
  docId: string,
13
  tableId: string,
14
  filter: string | undefined,
15
  sort: string | undefined,
16
  limit: string | undefined,
17
  hidden: string | undefined,
18
  X_Sort: string,
19
  X_Limit: string,
20
) {
21
  const url = new URL(
22
    `https://${auth.host}/api/docs/${docId}/tables/${tableId}/records`,
23
  );
24
  for (const [k, v] of [
25
    ["filter", filter],
26
    ["sort", sort],
27
    ["limit", limit],
28
    ["hidden", hidden],
29
  ]) {
30
    if (v !== undefined && v !== "" && k !== undefined) {
31
      url.searchParams.append(k, v);
32
    }
33
  }
34
  const response = await fetch(url, {
35
    method: "GET",
36
    headers: {
37
      "X-Sort": X_Sort,
38
      "X-Limit": X_Limit,
39
      Authorization: "Bearer " + auth.apiKey,
40
    },
41
    body: undefined,
42
  });
43
  if (!response.ok) {
44
    const text = await response.text();
45
    throw new Error(`${response.status} ${text}`);
46
  }
47
  return await response.json();
48
}
49