Accessing the unprocessed information stored on Google Drive through the Google API

I'm attempting to retrieve data (folder Name, ID, type, etc) from my Google Drive using the googleapis library

Here's the code I am using:

const fetchGoogleDriveFiles = async () => {
    try {
      const response = await fetch(
        `https://www.googleapis.com/drive/v3/files?q=mimeType='application/vnd.google-apps.folder'&fields=files(id,name,mimeType,parents)`,
        {
          method: "GET", 
          headers: {
            Authorization: `Bearer ${session.accessToken}`,
          },
        }
      ); 
      if (response.ok) {
        const data = await response.json();
        console.log("Google Drive Files:", data.files);
      } else {
        console.error("Error fetching Google Drive files:", response.status);
      }
    } catch (error) {
      console.error("Error fetching Google Drive files:", error);
    }
  };

While this code successfully retrieves data, it seems to only return data that I have previously uploaded using an upload function. What I actually want is to retrieve all existing data in my drive such as folder name, id, mimetype, etc.

I am utilizing an API route for authentication as follows:

export const authOptions = ({
    providers: [
        GoogleProvider({
            clientId : process.env.GOOGLE_CLIENT_ID ?? "" ,
            clientSecret : process.env.GOOGLE_CLIENT_SECRET ?? "",
            authorization: { 
              params: 
              { 
                scope: "openid email profile https://www.googleapis.com/auth/drive.file" 
                //
              } 
            },
        })
    ],
    callbacks: {
      async jwt({token, user , account} : any){  
        if (account) {
          token.accessToken = account.access_token;
        }
        return token
      },
      async session({ session, token } : any) {
        const newSession = {
          ...session,
          accessToken: token.accessToken,
        }; 
        return newSession;
      },
    }
})
 
const handler = NextAuth(authOptions)
export {handler as GET, handler as POST}

Can anyone assist me with understanding why I am not getting the desired results? Thanks!

Answer №1

Limitations may exist within your current scope of

https://www.googleapis.com/auth/drive.file
, as it only allows access to files and folders created by the same client.

If you aim to retrieve all existing data from your drive, including folder names, ids, member types, and more, it is necessary to update the scope accordingly.

Update Scope:

From: https://www.googleapis.com/auth/drive.file
To: https://www.googleapis.com/auth/drive.metadata.readonly

The new scope grants access to file metadata of all files and folders. For both file metadata and content retrieval, consider using

https://www.googleapis.com/auth/drive.readonly
. To manage file content and metadata for all files and folders, utilize
https://www.googleapis.com/auth/drive
.

Important Note:

  • Queries with the current parameters will only return metadata for up to 100 folders. If you need all files and folders, adjust using pageSize and pageToken. Exercise caution when making these adjustments.

Additional Resources:

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

Is it possible to create personalized BBCode?

I currently manage my own forum where users can edit, delete, and report posts and replies. However, I am now looking to add new features such as BBCode. Specifically, I want to implement a [QUOTE][/QUOTE] feature that allows users to easily quote other po ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

Utilize the HTTP.get function to serve files in the img src attribute

I am facing an issue where my file can only be accessed if I include an x-authentication token in the header of the "GET" http request. Unfortunately, using a cookie is not an option in this case. This means I cannot simply call for the file by its URL in ...

What is the best way to gather the "name" and "value" attributes from a designated section of a form using JavaScript and store them in an array?

How can I extract the "name" and "value" attributes from a specific section of a form and store them in an array using JavaScript? Here is the section of the form in question: <div class="multiPickerForm"> <input type="text" name="Id" value="1"& ...

Caution: Material-UI alert - the validation of DOM nesting indicates that a <p> element is not permitted within another <p> element

Upon interacting with the Collapse component in my Material UI table, I encounter this error: validateDOMNesting(...): <p> cannot appear as a descendant of <p>. ** I have come across a similar issue on Stack Overflow related to Typography, but ...

Exploring data visualization and time zones with highcharts on a React platform

I am working on a chart component in React that is populated with data from an API. The array of objects I receive contains rows structured like this: Rows: [ { EffectiveTime: "06-Nov-2020 00:00:00", FieldName: "GEN_EXP", Re ...

How can we effectively manage events that require coordination across multiple components?

In my latest project, I am working on developing a mobile-first application. My plan is to include a navbar at the top of the screen and a slide-in menu on the left side that will be accessible on every page or view. The current layout of my architecture ...

Retrieve information based on ID with AJAX in JSON format on ASP.NET

Here is a method from my web service: List<object[]> List1 = new List<object[]>(); [WebMethod(EnableSession = true)] [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.Respons ...

Tips for showcasing several images with accompanying content once the webpage has finished loading

I am faced with an issue on my PHP website. The website is a social networking platform with numerous images and contents. I am seeking a way to first display only the content to the user, then show the images after they have all finished loading. Addition ...

An issue arises when request.body appears blank within the context of node.js, express, and body

I am currently attempting to send a request to my node server. Below is the xhttp request being made. let parcel = { userId: userId, //string unitid: unitid, //string selections: selections //array }; // Making a Call to the Server using XMLHttpR ...

Utilize Mapbox as the source for VGeosearch services

Utilizing mapbox as a provider for VGeosearch has been my recent project. In certain scenarios where the user is Chinese, I need to initialize a map using mapbox (due to coordinate rules) and in other cases utilize Google maps. All of this is managed thro ...

When working with environment variables in Node.js, everything runs smoothly within the console log. However, an error occurs when attempting to pass a parameter to

In my current project setup with nx monorepo and TypeScript for handling environment variables in Node.js, I encountered a peculiar issue. I am able to access the variables using console.log, but when I pass the variable as a parameter to the mongoose.conn ...

Enhance Axios to support receiving a URL in the form of a URL address

I am currently developing a TypeScript project where I am utilizing Axios to send GET requests to different URLs. In order to streamline the process, I am using the NodeJS URL interface to handle my URLs. However, it seems that Axios only accepts URLs in s ...

Troubleshooting Problem with Scrolling to the Bottom of a DIV Using J

I've been experimenting with creating a chat box in jQuery that automatically scrolls to the bottom when the page loads. I've tried various methods, but most of them haven't worked as expected. One method I found animates a scroll down, but ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

"Mastering the art of event delegation: A guide to effectively engaging with various

I have data that is generated dynamically, as shown in the snippet below: const resultsDiv = document.getElementById("results"); const getList = document.getElementById("example"); document.querySelector(".container").addEventListener("click", function ...

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

Exploring Nested Routes and Queries in Vue JS

As a beginner in Vue, I have been exploring a demo project and struggling with understanding how routes with query parameters function. The documentation suggests using router.push({ path: 'register', query: { plan: 'private' }}) to gen ...