0

Find Documents

by
Published today

Search the account's Google Docs by name or content. Requires drive.readonly or drive on the connection.

Script gdocs Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 hours ago
1
//native
2

3
/**
4
 * Find Documents
5
 * Search the Google Docs the account can see (shared drives included), newest-modified first. `query` matches the title or full text; leave it empty to list all docs. Pass the returned `nextPageToken` as `page_token` for the next page. Requires drive.readonly or drive on the connection (drive.file only sees docs this connection created).
6
 */
7
export async function main(
8
  auth: RT.Gdocs,
9
  query: string | undefined,
10
  page_size: number = 50,
11
  page_token: string | undefined
12
) {
13
  let q = "mimeType = 'application/vnd.google-apps.document' and trashed = false"
14
  if (query) {
15
    const escaped = query.replace(/\\/g, "\\\\").replace(/'/g, "\\'")
16
    q += ` and (name contains '${escaped}' or fullText contains '${escaped}')`
17
  }
18
  const url = new URL("https://www.googleapis.com/drive/v3/files")
19
  url.searchParams.append("q", q)
20
  url.searchParams.append(
21
    "fields",
22
    "nextPageToken,files(id,name,modifiedTime,webViewLink,owners(emailAddress))"
23
  )
24
  url.searchParams.append("orderBy", "modifiedTime desc")
25
  url.searchParams.append("pageSize", String(page_size || 50))
26
  url.searchParams.append("supportsAllDrives", "true")
27
  url.searchParams.append("includeItemsFromAllDrives", "true")
28
  if (page_token != null && page_token !== "")
29
    url.searchParams.append("pageToken", page_token)
30

31
  const response = await fetch(url, {
32
    headers: {
33
      Authorization: `Bearer ${auth.token}`,
34
      Accept: "application/json",
35
    },
36
  })
37
  if (!response.ok) {
38
    throw new Error(`${response.status} ${await response.text()}`)
39
  }
40

41
  return await response.json()
42
}
43