//native
/**
* Get Folder ID for Path
* 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.
*/
export async function main(
auth: RT.Gdrive,
path: string,
root_folder_id: string = "root"
) {
let folder = { id: root_folder_id || "root", name: "" }
for (const name of path.split("/").filter((p) => p !== "")) {
const url = new URL("https://www.googleapis.com/drive/v3/files")
url.searchParams.append(
"q",
`name = '${name.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}' and '${folder.id}' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false`
)
url.searchParams.append("fields", "files(id, name)")
url.searchParams.append("orderBy", "createdTime")
url.searchParams.append("pageSize", "1")
url.searchParams.append("supportsAllDrives", "true")
url.searchParams.append("includeItemsFromAllDrives", "true")
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${auth.token}`,
Accept: "application/json",
},
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { files } = (await response.json()) as {
files: { id: string; name: string }[]
}
if (files.length === 0) return null
folder = files[0]
}
return folder
}
Submitted by hugo989 2 hours ago