1 | import { mapValues } from 'lodash-es' |
2 |
|
3 |
|
4 | type Grist = { |
5 | token: string, |
6 | teamOrBaseURL: string |
7 | } |
8 |
|
9 | type GristDoc = { |
10 | doc: string, |
11 | gristInstance: Grist |
12 | } |
13 |
|
14 | export async function main( |
15 | gristDoc: GristDoc, |
16 | table: string, |
17 | params?: { filter?: Object, sort?: string, limit?: number, hidden?: boolean }, |
18 | ): Promise<any> { |
19 | const { gristInstance: grist, doc } = gristDoc |
20 |
|
21 | |
22 | const baseURL = grist.teamOrBaseURL.includes('.') ? grist.teamOrBaseURL : `https://${grist.teamOrBaseURL}.getgrist.com` |
23 | let paramsString = '' |
24 | if (params) { |
25 | const encodedParams = new URLSearchParams(mapValues(params, v => typeof v === 'string' ? v : JSON.stringify(v))).toString() |
26 | paramsString = `?${encodedParams}` |
27 | } |
28 | console.log(paramsString) |
29 | const response = await fetch( |
30 | `${baseURL}/api/docs/${doc}/tables/${table}/records` |
31 | + paramsString, |
32 | { |
33 | method: 'GET', |
34 | headers: { |
35 | 'Authorization': `Bearer ${grist.token}`, |
36 | 'Content-Type': 'application/json' |
37 | }, |
38 | }); |
39 |
|
40 | if (!response.ok) { |
41 | throw new Error(`Failed to write to Grist table: ${response.statusText} ${JSON.stringify(await response.json())}`); |
42 | } |
43 |
|
44 | return await response.json(); |
45 | } |
46 |
|