1 | |
2 |
|
3 | |
4 | * Get Folder ID for Path |
5 | * Resolve a folder path such as `Reports/2026/Q3` to the id of its last folder, walking down from `root_folder_id` (default: the root of My Drive; pass a shared drive id to start there). Returns `{ id, name }`, or null when a segment doesn't exist. If several folders share a name, the oldest is used. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Gdrive, |
9 | path: string, |
10 | root_folder_id: string = "root" |
11 | ) { |
12 | let folder = { id: root_folder_id || "root", name: "" } |
13 | for (const name of path.split("/").filter((p) => p !== "")) { |
14 | const url = new URL("https://www.googleapis.com/drive/v3/files") |
15 | url.searchParams.append( |
16 | "q", |
17 | `name = '${name.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}' and '${folder.id}' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false` |
18 | ) |
19 | url.searchParams.append("fields", "files(id, name)") |
20 | url.searchParams.append("orderBy", "createdTime") |
21 | url.searchParams.append("pageSize", "1") |
22 | url.searchParams.append("supportsAllDrives", "true") |
23 | url.searchParams.append("includeItemsFromAllDrives", "true") |
24 |
|
25 | const response = await fetch(url, { |
26 | headers: { |
27 | Authorization: `Bearer ${auth.token}`, |
28 | Accept: "application/json", |
29 | }, |
30 | }) |
31 | if (!response.ok) { |
32 | throw new Error(`${response.status} ${await response.text()}`) |
33 | } |
34 | const { files } = (await response.json()) as { |
35 | files: { id: string; name: string }[] |
36 | } |
37 | if (files.length === 0) return null |
38 | folder = files[0] |
39 | } |
40 | return folder |
41 | } |
42 |
|