1 | |
2 |
|
3 | |
4 | * Delete Table |
5 | * Delete a table from a Google Doc by its 1-based position among the body's top-level tables (tables nested in another table's cell are not counted). Set `tab_id` (from List Tabs) to target a tab other than the first. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Gdocs, |
9 | document_id: string, |
10 | table_number: number = 1, |
11 | tab_id: string | undefined |
12 | ) { |
13 | const url = new URL(`https://docs.googleapis.com/v1/documents/${document_id}`) |
14 | if (tab_id) url.searchParams.append("includeTabsContent", "true") |
15 | const doc = await call(url) |
16 | let content = doc.body?.content |
17 | if (tab_id) { |
18 | const find = (tabs: any[]): any => |
19 | tabs |
20 | .map((t) => (t.tabProperties.tabId === tab_id ? t : find(t.childTabs ?? []))) |
21 | .find(Boolean) |
22 | content = find(doc.tabs ?? [])?.documentTab?.body?.content |
23 | if (!content) throw new Error(`No tab ${tab_id} in document ${document_id}`) |
24 | } |
25 | const tables = content.filter((el: any) => el.table) |
26 | const n = table_number || 1 |
27 | const table = tables[n - 1] |
28 | if (!table) { |
29 | throw new Error( |
30 | `Table ${n} not found: the document has ${tables.length} table(s)` |
31 | ) |
32 | } |
33 |
|
34 | return await call( |
35 | `https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`, |
36 | { |
37 | requests: [ |
38 | { |
39 | deleteContentRange: { |
40 | range: { |
41 | startIndex: table.startIndex, |
42 | endIndex: table.endIndex, |
43 | tabId: tab_id || undefined, |
44 | }, |
45 | }, |
46 | }, |
47 | ], |
48 | } |
49 | ) |
50 |
|
51 | async function call(url: string | URL, body?: object) { |
52 | const response = await fetch(url, { |
53 | method: body ? "POST" : "GET", |
54 | headers: { |
55 | Authorization: `Bearer ${auth.token}`, |
56 | ...(body ? { "Content-Type": "application/json" } : {}), |
57 | Accept: "application/json", |
58 | }, |
59 | body: body ? JSON.stringify(body) : undefined, |
60 | }) |
61 | if (!response.ok) { |
62 | throw new Error(`${response.status} ${await response.text()}`) |
63 | } |
64 | return await response.json() |
65 | } |
66 | } |
67 |
|