//native
/**
* Delete Table
* 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.
*/
export async function main(
auth: RT.Gdocs,
document_id: string,
table_number: number = 1,
tab_id: string | undefined
) {
const url = new URL(`https://docs.googleapis.com/v1/documents/${document_id}`)
if (tab_id) url.searchParams.append("includeTabsContent", "true")
const doc = await call(url)
let content = doc.body?.content
if (tab_id) {
const find = (tabs: any[]): any =>
tabs
.map((t) => (t.tabProperties.tabId === tab_id ? t : find(t.childTabs ?? [])))
.find(Boolean)
content = find(doc.tabs ?? [])?.documentTab?.body?.content
if (!content) throw new Error(`No tab ${tab_id} in document ${document_id}`)
}
const tables = content.filter((el: any) => el.table)
const n = table_number || 1
const table = tables[n - 1]
if (!table) {
throw new Error(
`Table ${n} not found: the document has ${tables.length} table(s)`
)
}
return await call(
`https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`,
{
requests: [
{
deleteContentRange: {
range: {
startIndex: table.startIndex,
endIndex: table.endIndex,
tabId: tab_id || undefined,
},
},
},
],
}
)
async function call(url: string | URL, body?: object) {
const response = await fetch(url, {
method: body ? "POST" : "GET",
headers: {
Authorization: `Bearer ${auth.token}`,
...(body ? { "Content-Type": "application/json" } : {}),
Accept: "application/json",
},
body: body ? JSON.stringify(body) : undefined,
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
}
Submitted by hugo989 6 hours ago