Edits history of script submission #23521 for ' Search Files (ms_onedrive)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    const graph = "https://graph.microsoft.com/v1.0"
    
    function driveUrl(drive_id: string | undefined) {
      return drive_id != null && drive_id !== ""
        ? `${graph}/drives/${encodeURIComponent(drive_id)}`
        : `${graph}/me/drive`
    }
    
    /**
     * Search Files
     * 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.
     */
    export async function main(
      auth: RT.MsOnedrive,
    
      query: string,
      select: string | undefined,
      top: number = 50,
      next_link: string | undefined,
      drive_id: string | undefined
    ) {
      const drive = driveUrl(drive_id)
      if (
        next_link != null &&
        next_link !== "" &&
        !next_link.startsWith("https://graph.microsoft.com/")
      ) {
        throw new Error(
          "next_link must be an @odata.nextLink returned by Microsoft Graph"
        )
      }
      let url: URL
      if (next_link != null && next_link !== "") {
        url = new URL(next_link)
      } else {
        url = new URL(
          `${drive}/root/search(q='${encodeURIComponent(query.replace(/'/g, "''"))}')`
        )
        url.searchParams.append("$top", String(top))
        if (select != null && select !== "") {
          url.searchParams.append("$select", select)
        }
      }
    
      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
        },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 5 hours ago