1 | |
2 |
|
3 | export type DynSelect_sheet_name = string |
4 |
|
5 | |
6 | export async function sheet_name(auth: RT.Gsheets, spreadsheet_id: string) { |
7 | const response = await fetch( |
8 | `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}?fields=sheets.properties.title`, |
9 | { |
10 | headers: { |
11 | Authorization: `Bearer ${auth.token}`, |
12 | Accept: "application/json", |
13 | }, |
14 | } |
15 | ) |
16 | if (!response.ok) { |
17 | throw new Error(`${response.status} ${await response.text()}`) |
18 | } |
19 | const { sheets } = (await response.json()) as { |
20 | sheets: { properties: { title: string } }[] |
21 | } |
22 | return sheets.map((s) => ({ |
23 | value: s.properties.title, |
24 | label: s.properties.title, |
25 | })) |
26 | } |
27 |
|
28 | |
29 | * Get Cell |
30 | * Read one cell (e.g. `B2`) and return its value, or null when empty. `FORMATTED_VALUE` returns what the cell displays, `UNFORMATTED_VALUE` the raw number/boolean, `FORMULA` the formula. |
31 | */ |
32 | export async function main( |
33 | auth: RT.Gsheets, |
34 | spreadsheet_id: string, |
35 | sheet_name: DynSelect_sheet_name, |
36 | cell: string, |
37 | value_render_option: |
38 | "FORMATTED_VALUE" | "UNFORMATTED_VALUE" | "FORMULA" = "FORMATTED_VALUE" |
39 | ) { |
40 | const range = encodeURIComponent( |
41 | `'${sheet_name.replaceAll("'", "''")}'!${cell}` |
42 | ) |
43 | const url = new URL( |
44 | `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}/values/${range}` |
45 | ) |
46 | url.searchParams.append("valueRenderOption", value_render_option) |
47 |
|
48 | const response = await fetch(url, { |
49 | headers: { |
50 | Authorization: `Bearer ${auth.token}`, |
51 | Accept: "application/json", |
52 | }, |
53 | }) |
54 |
|
55 | if (!response.ok) { |
56 | throw new Error(`${response.status} ${await response.text()}`) |
57 | } |
58 |
|
59 | const { values } = (await response.json()) as { values?: any[][] } |
60 | return values?.[0]?.[0] ?? null |
61 | } |
62 |
|