1 | |
2 |
|
3 | const graph = "https://graph.microsoft.com/v1.0" |
4 |
|
5 | function driveUrl(drive_id: string | undefined) { |
6 | return drive_id != null && drive_id !== "" |
7 | ? `${graph}/drives/${encodeURIComponent(drive_id)}` |
8 | : `${graph}/me/drive` |
9 | } |
10 |
|
11 | |
12 | function ref(item: string | undefined) { |
13 | if (item == null || item === "" || item === "/") return "root" |
14 | if (!item.startsWith("/")) return `items/${encodeURIComponent(item)}` |
15 | const path = item |
16 | .replace(/\/+$/, "") |
17 | .split("/") |
18 | .map(encodeURIComponent) |
19 | .join("/") |
20 | return `root:${path}:` |
21 | } |
22 |
|
23 | |
24 | * List Files in Folder |
25 | * List the files and folders directly inside a folder (the root when `folder` is empty) in your OneDrive, or in another drive when `drive_id` is set. `folder` is an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). `filter` and `order_by` take OData (e.g. `name desc`). Pass the returned `@odata.nextLink` as `next_link` for the next page. Requires Files.Read (covered by the default Files.ReadWrite); a drive that is not your own needs Files.Read.All. |
26 | */ |
27 | export async function main( |
28 | auth: RT.MsOnedrive, |
29 |
|
30 | folder: string | undefined, |
31 | order_by: string | undefined, |
32 | filter: string | undefined, |
33 | select: string | undefined, |
34 | top: number = 100, |
35 | next_link: string | undefined, |
36 | drive_id: string | undefined |
37 | ) { |
38 | const drive = driveUrl(drive_id) |
39 | if ( |
40 | next_link != null && |
41 | next_link !== "" && |
42 | !next_link.startsWith("https://graph.microsoft.com/") |
43 | ) { |
44 | throw new Error( |
45 | "next_link must be an @odata.nextLink returned by Microsoft Graph" |
46 | ) |
47 | } |
48 | let url: URL |
49 | if (next_link != null && next_link !== "") { |
50 | url = new URL(next_link) |
51 | } else { |
52 | url = new URL(`${drive}/${ref(folder)}/children`) |
53 | url.searchParams.append("$top", String(top)) |
54 | if (order_by != null && order_by !== "") { |
55 | url.searchParams.append("$orderby", order_by) |
56 | } |
57 | if (filter != null && filter !== "") { |
58 | url.searchParams.append("$filter", filter) |
59 | } |
60 | if (select != null && select !== "") { |
61 | url.searchParams.append("$select", select) |
62 | } |
63 | } |
64 |
|
65 | const response = await fetch(url, { |
66 | headers: { |
67 | Authorization: `Bearer ${auth.token}`, |
68 | Accept: "application/json", |
69 | }, |
70 | }) |
71 |
|
72 | if (!response.ok) { |
73 | throw new Error(`${response.status} ${await response.text()}`) |
74 | } |
75 |
|
76 | return await response.json() |
77 | } |
78 |
|