0

Search Files

by
Published today

Search files and folders by name, metadata and content in your OneDrive, or in another drive when `drive_id` is set. Results come from the search index, so a file created seconds ago may not appear yet. 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.

Script ms_onedrive Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
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
 * Search Files
13
 * Search files and folders by name, metadata and content in your OneDrive, or in another drive when `drive_id` is set. Results come from the search index, so a file created seconds ago may not appear yet. 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.
14
 */
15
export async function main(
16
  auth: RT.MsOnedrive,
17

18
  query: string,
19
  select: string | undefined,
20
  top: number = 50,
21
  next_link: string | undefined,
22
  drive_id: string | undefined
23
) {
24
  const drive = driveUrl(drive_id)
25
  if (
26
    next_link != null &&
27
    next_link !== "" &&
28
    !next_link.startsWith("https://graph.microsoft.com/")
29
  ) {
30
    throw new Error(
31
      "next_link must be an @odata.nextLink returned by Microsoft Graph"
32
    )
33
  }
34
  let url: URL
35
  if (next_link != null && next_link !== "") {
36
    url = new URL(next_link)
37
  } else {
38
    url = new URL(
39
      `${drive}/root/search(q='${encodeURIComponent(query.replace(/'/g, "''"))}')`
40
    )
41
    url.searchParams.append("$top", String(top))
42
    if (select != null && select !== "") {
43
      url.searchParams.append("$select", select)
44
    }
45
  }
46

47
  const response = await fetch(url, {
48
    headers: {
49
      Authorization: `Bearer ${auth.token}`,
50
      Accept: "application/json",
51
    },
52
  })
53

54
  if (!response.ok) {
55
    throw new Error(`${response.status} ${await response.text()}`)
56
  }
57

58
  return await response.json()
59
}
60