Leveraging the power of NextJs and the googleapis Patch function to seamlessly relocate files and folders to a specific

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.

Answer №1

After some troubleshooting, I was able to resolve the issue. Initially, I was confused about the Google Docs path parameters and query parameters. I had been attempting to use addParent and removeParent within a body request, but I realized they should have been used in the Path parameters instead.

Thankfully, everything is functioning correctly now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am unable to retrieve the values from a manually created JavaScript list using querySelectorAll()

const myList = document.createElement("div"); myList.setAttribute('id', 'name'); const list1 = document.createElement("ul"); const item1 = document.createElement("li"); let value1 = document.createTe ...

Drag components on the React Grid Layout using only movement

Currently developing a project with React-Grid-Layout involving the arrangement of multiple widgets in a layout that can be moved and resized. This interactive feature allows users to engage with the widgets. However, I have encountered an issue where cli ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

Struggling to align a div in the middle using react and tailwindcss

Struggling to center a div in React with Tailwind, no matter what method I try. Here is my code: "use client"; import Image from "next/image"; import React from "react"; const LoginPage = () => { return ( <div cla ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

The child module invokes a function within the parent module and retrieves a result

Guardian XML <tr [onSumWeights]="sumWeights" > Algorithm sumWeights(): number { return // Calculate total value of all weights } Offspring @Input() onTotalWeights: () => number; canMakeChanges() { return this.onTota ...

`AngularJS Voice Recognition Solutions`

In my quest to implement voice recognition in an AngularJS application I'm developing for Android and Electron, I've encountered some challenges. While I've already discovered a suitable solution for Android using ng-speech-recognition, fin ...

What is the process for creating a personalized user interface for NextAuth.js that integrates with AWS Cognito?

Can I create a unique user interface for AWS Cognito with NextAuth.js? Whenever I use the NextAuth.js API, I am presented with a rather unattractive screen containing just a button that redirects to the actual AWS Cognito sign-in page. Although the AWS Co ...

The state data is not being updated prior to making the fetch request

Currently delving into the world of Next.js and React after working with Angular/Svelte, I quickly put together a rough POC but encountered an issue where my data doesn't update. In this specific scenario, completed_at starts off empty when I submit ...

Transfer data via a POST request to the following API

Is there a way to send a media file as form data to an API in Next.js, so that I can perform certain tasks on it using Node.js? User Interface Upon clicking, use the command query("/api/upload/", image), where 'image' represents the file to be ...

Mastering the art of theming components using styled-components and Material-UI

Can you integrate the Material-UI "theme"-prop with styled-components using TypeScript? Here is an example of Material-UI code: const useStyles = makeStyles((theme: Theme) => ({ root: { background: theme.palette.primary.main, }, })); I attemp ...

The properties in Typescript, specifically 'value', are not compatible with each other

I've encountered an error while working on a TypeScript project with React Context. The error message states: Argument of type 'Context<{}>' is not assignable to parameter of type 'Context<IsProductContext>'. The type ...

What is the best way to retrieve data from an entity with Prisma where the number of its children exceeds a certain threshold?

I am working on a project where I have an entity called Author that can have multiple Books associated with it. My goal is to retrieve all Authors who have more than 5 books in my database. The application is built using Prisma in conjunction with Next.js ...

Struggling to find a solution for directing to the featured homes page without the content overlapping with my navbar and search component. Any assistance would be greatly

Looking for assistance with routing to the featured homes page without the content overlapping my navbar and search component. I simply want it to direct to a new URL without importing the components unless specifically needed. Check out this link I suspe ...

Can classes be encapsulated within a NgModule in Angular 2/4?

Looking to organize my classes by creating a module where I can easily import them like a separate package. Take a look at this example: human.ts (my class file) export class Human { private numOfLegs: Number; constructor() { this.numOfLegs = 2 ...

Tips for displaying a component using props obtained from the NextJS router

I'm attempting to display a component that utilizes a dynamic router path prop. My goal is for mysite.com/something to trigger the component with the something prop. If the route becomes mysite.com/somethingelse, I want the component to receive the so ...

In TypeScript, what is the return Type of sequelize.define()?

After hearing great things about TypeScript and its benefits of static typing, I decided to give it a try. I wanted to test it out by creating a simple web API with sequelize, but I'm struggling to understand the types returned from sequelize. Here ar ...

There was an error trying to read properties of undefined, specifically the 'prototype', in a code using Next.Js and Express

While attempting to incorporate express into my next.js project, I encountered errors when trying to initialize express: const express = require('express'); The errors that appeared were: Module not found: Can't resolve 'async_hooks ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Tips for resolving the error: finding the right loader for handling specific file types in React hooks

data = [{ img: '01d' }, { img: '02d' }] data && data.map((item) => ( <img src={require(`./icons/${item['img']}.svg`).default} /> )) I am facing an issue with the message Error: Module parse failed: U ...