Search code examples
javascriptgoogle-drive-apigoogle-api-js-client

Google Drive API v3 find all files in folder and children


I have google api client for java script I created all requests. Last request in my app it is get all files in folder and children folders. It is request get all files in parent folder.

   let files = await obj.staticProperty.gapi.client.drive.files.list({
                'q': `'${object['folder']['id']}' in parents`,
                'pageSize': 10
            })

How can i get also all files in children folders ?


Solution

  • I do it recursively, note that I have a callback that collects files - I'm using Redux with React so it just dispatches an action that adds the bunch of files to the state each time the method gets more files:

    function getAllFiles(bearerToken, pageToken = undefined, q = undefined,
                         callback = (files) => console.log('No callback provided',
                             files),
                         onComplete = () => console.log('No onComplete provided'),
    ) {
      axios.get('https://www.googleapis.com/drive/v3/files', {
        params: {
          corpora: 'user',
          fields: 'files(id,name,size,mimeType,parents,webViewLink,trashed),nextPageToken',
          // q: 'mimeType = \'application/vnd.google-apps.folder\'',
          q: q,
          pageSize: 1000,
          pageToken: pageToken,
        },
        headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer ' + bearerToken,
        },
      }).then((result) => {
        callback(result.data.files);
        if (result.data.nextPageToken) {
          getAllFiles(bearerToken, result.data.nextPageToken, q, callback,
              onComplete);
        } else {
          onComplete();
        }
      }).catch((error) => {
        console.error('Error folders result', error);
      });
    }
    

    This is from the code for my "Drive Dashboard" at https://drivedashboard.saisols.com/