//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`
}
// An item is addressed by its id, or by a path from the drive root starting with "/"
function ref(item: string | undefined) {
if (item == null || item === "" || item === "/") return "root"
if (!item.startsWith("/")) return `items/${encodeURIComponent(item)}`
const path = item
.replace(/\/+$/, "")
.split("/")
.map(encodeURIComponent)
.join("/")
return `root:${path}:`
}
async function folderId(
token: string,
drive: string,
folder: string
): Promise<string> {
if (!folder.startsWith("/")) return folder
const response = await fetch(`${drive}/${ref(folder)}?$select=id`, {
headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return ((await response.json()) as { id: string }).id
}
/**
* Move or Rename File or Folder
* Move a file or folder to another folder of the same drive, rename it, or both. `item` and `destination_folder` are each an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). To move across drives, copy then delete. Requires Files.ReadWrite (a connection default); a drive that is not your own needs Files.ReadWrite.All.
*/
export async function main(
auth: RT.MsOnedrive,
item: string,
destination_folder: string | undefined,
new_name: string | undefined,
drive_id: string | undefined
) {
const drive = driveUrl(drive_id)
const body: { [key: string]: any } = {}
if (new_name != null && new_name !== "") body.name = new_name
if (destination_folder != null && destination_folder !== "") {
body.parentReference = {
id: await folderId(auth.token, drive, destination_folder),
}
}
if (Object.keys(body).length === 0) {
throw new Error("Provide destination_folder, new_name or both")
}
const response = await fetch(`${drive}/${ref(item)}`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${auth.token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
Submitted by hugo989 5 hours ago