//native
/**
* Get Document as Text
* Get a Google Doc's title and its body as plain text (paragraphs and table cells, in reading order). Only the first tab of a multi-tab document is read.
*/
export async function main(auth: RT.Gdocs, document_id: string) {
const response = await fetch(
`https://docs.googleapis.com/v1/documents/${document_id}`,
{
headers: {
Authorization: `Bearer ${auth.token}`,
Accept: "application/json",
},
}
)
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const doc = await response.json()
return {
document_id: doc.documentId,
title: doc.title,
text: toText(doc.body?.content ?? []),
}
}
function toText(content: any[]): string {
let text = ""
for (const el of content) {
for (const e of el.paragraph?.elements ?? [])
text += e.textRun?.content ?? ""
for (const row of el.table?.tableRows ?? [])
for (const cell of row.tableCells ?? [])
text += toText(cell.content ?? [])
if (el.tableOfContents) text += toText(el.tableOfContents.content ?? [])
}
return text
}
Submitted by hugo989 4 hours ago