0
Fetch data from a table
One script reply has been approved by the moderators Verified

Deprecated in favor of records endpoints. We have no immediate plans to remove these endpoints, but consider records a better starting point for new projects.

Created by hugo697 93 days ago Viewed 3612 times
0
Submitted by hugo697 Bun
Verified 93 days ago
1
//native
2
type Grist = {
3
  apiKey: string;
4
  host: string;
5
};
6
/**
7
 * Fetch data from a table
8
 * Deprecated in favor of `records` endpoints. We have no immediate plans to remove these endpoints, but consider `records` a better starting point for new projects.
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
  X_Sort: string,
18
  X_Limit: string,
19
) {
20
  const url = new URL(
21
    `https://${auth.host}/api/docs/${docId}/tables/${tableId}/data`,
22
  );
23
  for (const [k, v] of [
24
    ["filter", filter],
25
    ["sort", sort],
26
    ["limit", limit],
27
  ]) {
28
    if (v !== undefined && v !== "" && k !== undefined) {
29
      url.searchParams.append(k, v);
30
    }
31
  }
32
  const response = await fetch(url, {
33
    method: "GET",
34
    headers: {
35
      "X-Sort": X_Sort,
36
      "X-Limit": X_Limit,
37
      Authorization: "Bearer " + auth.apiKey,
38
    },
39
    body: undefined,
40
  });
41
  if (!response.ok) {
42
    const text = await response.text();
43
    throw new Error(`${response.status} ${text}`);
44
  }
45
  return await response.json();
46
}
47