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 | * Update Cell |
30 | * Write one cell (e.g. `B2`). With `USER_ENTERED` the value is parsed as if typed in the UI (formulas like `=SUM(A1:A9)`, dates, numbers); `RAW` stores it as-is. |
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: any, |
38 | value_input_option: "USER_ENTERED" | "RAW" = "USER_ENTERED" |
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("valueInputOption", value_input_option) |
47 | url.searchParams.append("includeValuesInResponse", "true") |
48 |
|
49 | const response = await fetch(url, { |
50 | method: "PUT", |
51 | headers: { |
52 | Authorization: `Bearer ${auth.token}`, |
53 | "Content-Type": "application/json", |
54 | Accept: "application/json", |
55 | }, |
56 | body: JSON.stringify({ values: [[value]] }), |
57 | }) |
58 |
|
59 | if (!response.ok) { |
60 | throw new Error(`${response.status} ${await response.text()}`) |
61 | } |
62 |
|
63 | return await response.json() |
64 | } |
65 |
|