Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google API, drive.files.list and returning child files only

I am using the 'googleapis' library in NodeJS and I am trying to return the list of files and folders in the currently specified folder, but instead I find drive.files.list returns all files that the user has been granted permissions to read.

My goal is to be able to download the folder structure below a given folder, that then could be consumed by the NodeJS application in a meaningful way.

The code I am using is as follows:

const fs = require('fs');
const google = require('googleapis');
const OAuth2 = google.auth.OAuth2;
const key = require('./key.json');

const jwtClient = new google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  ['https://www.googleapis.com/auth/drive'],
  null
);

const drive = google.drive({
  version: 'v3',
  auth: jwtClient
});

jwtClient.authorize(function (err, tokens) {
  if (err) {
    console.log(err);
    return;
  }

  // Make an authorized request to list Drive files.
  drive.files.list({
     includeRemoved: false,
     spaces: 'drive',
     fileId: 'the-file-id-of-the-folder'
  }, function (err, resp) {
    if (!err) {
        var i;
        var files = resp.files;
        for (i=0; i<files.length; i++) {
            if (files[i].mimeType !== 'application/vnd.google-apps.folder') {
                console.log('file: ' + files[i].name);
            } else {
                console.log('directory: ' + files[i].name);
            }
            console.log(files[i]);
        }
    } else {
        console.log('error: ', err);
    }
  });
});

Note I did try the drive.files.get endpoint, without the alt: 'media' parameter, but it does not seem to return any more metadata that the drive.files.list call.

like image 285
Andre M Avatar asked Dec 24 '22 22:12

Andre M


1 Answers

Further exploration leads to the 'Search Parameters' page, which indicates in v3 of the API there is also the 'fields' and 'q' parameters, such that, the list operations becomes (ES6 code):

var fileId = '0B0gSXXXXXXXXXXXXXXXXb0hpaWM'
drive.files.list({
    includeRemoved: false,
    spaces: 'drive',
    fileId: fileId,
    fields: 'nextPageToken, files(id, name, parents, mimeType, modifiedTime)',
    q: `'${fileId}' in parents`
}, function (err, response) {
   // TODO handle response
});

Note, for other metadata, see:

https://developers.google.com/drive/v3/reference/files#resource

like image 111
Andre M Avatar answered Dec 28 '22 10:12

Andre M