I am currently working on a functionality to move specific files or folders to another folder using nextjs + googleapis. Here is the code I have been testing:
const moveFileOrFolder = async () => {
if (!session || !selectedItemId || !destinationFolderId) return;
try {
const auth = `Bearer ${session.accessToken}`;
// Fetch the current parents of the selected item
const response = await fetch(
`https://www.googleapis.com/drive/v3/files/${selectedItemId}?fields=id,name,parents`,
{
method: "GET",
headers: {
Authorization: auth,
},
}
);
console.log("Response" , selectedItemId)
if (response.ok) {
const data = await response.json();
// Prepare the current parents
const currentParents = data.parents || [];
// Check if the destination folder is already a parent
if (currentParents.includes(destinationFolderId)) {
console.error("The destination folder is already a parent of the selected item.");
return;
}
// Prepare the request to move the file/folder
const updateResponse = await fetch(
`https://www.googleapis.com/drive/v3/files/${destinationFolderId}?fields=id,name`,
{
method: "PATCH",
headers: {
Authorization: auth,
"Content-Type": "application/json",
},
body: JSON.stringify({
addParents: destinationFolderId, // Specify the new parent
removeParents: currentParents.join(','), // Specify the current parents to remove
}),
}
);
console.log("Update Response" , destinationFolderId)
if (updateResponse.ok) {
console.log("File/Folder moved successfully!" , updateResponse);
} else {
const errorData = await updateResponse.json();
console.error("Error moving file/folder:", updateResponse.status, errorData);
}
} else {
const errorData = await response.json();
console.error("Error fetching file/folder details:", response.status, errorData);
}
} catch (error) {
console.error("Error moving file/folder:", error);
}
};
After adding the necessary fields for addParent and removeParent as suggested by the error message, I was able to receive a success message indicating that the file or folder has been moved. However, the changes are not reflecting in my Google Drive. I have also verified my API routes including Patch scopes.
If anyone can provide insights on why the message shows success but no actual changes are being made, I would greatly appreciate it.