0

Run an SQL query against a document

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
 * Run an SQL query against a document
8
 *
9
 */
10
export async function main(auth: Grist, docId: string, q: string | undefined) {
11
  const url = new URL(`https://${auth.host}/api/docs/${docId}/sql`);
12
  for (const [k, v] of [["q", q]]) {
13
    if (v !== undefined && v !== "" && k !== undefined) {
14
      url.searchParams.append(k, v);
15
    }
16
  }
17
  const response = await fetch(url, {
18
    method: "GET",
19
    headers: {
20
      Authorization: "Bearer " + auth.apiKey,
21
    },
22
    body: undefined,
23
  });
24
  if (!response.ok) {
25
    const text = await response.text();
26
    throw new Error(`${response.status} ${text}`);
27
  }
28
  return await response.json();
29
}
30