0

List Spreadsheets

by
Published today

List or search the spreadsheets the connected account can open.

Script gsheets Verified

The script

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

3
/**
4
 * List Spreadsheets
5
 * List the spreadsheets the connected account can open, most recently modified first, optionally filtered by name. Uses the Drive API, so the connection needs drive.metadata.readonly (or drive.readonly / drive) on top of the spreadsheets scope. Returns `files` and `nextPageToken`.
6
 */
7
export async function main(
8
  auth: RT.Gsheets,
9
  name_contains: string | undefined,
10
  page_size: number = 100,
11
  page_token: string | undefined
12
) {
13
  let q =
14
    "mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false"
15
  if (name_contains != null && name_contains !== "")
16
    q += ` and name contains '${name_contains.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`
17

18
  const url = new URL("https://www.googleapis.com/drive/v3/files")
19
  url.searchParams.append("q", q)
20
  url.searchParams.append("orderBy", "modifiedTime desc")
21
  url.searchParams.append("pageSize", String(page_size))
22
  url.searchParams.append(
23
    "fields",
24
    "nextPageToken, files(id, name, modifiedTime, webViewLink, owners(displayName, emailAddress))"
25
  )
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

38
  if (!response.ok) {
39
    throw new Error(`${response.status} ${await response.text()}`)
40
  }
41

42
  return await response.json()
43
}
44