google drive | copy a file on google drive | download all docs as actual data files | Search

The code imports dependencies and creates a google object to simplify access to Google APIs, then defines two functions: listDriveFiles to list files in a specified Google Drive folder, and listDrive to list files in the root folder. The listDrive function is exported, and an optional section allows it to be executed using a $.sendResult method in a testing or debugging context.

Run example

npm run import -- "merge google drive"

merge google drive

var fs = require('fs');
var path = require('path');
var {GoogleAuth} = require('google-auth-library');
var importer = require('../Core')
var getRpcFromSpec = importer.import("get rpc from spec")
var authorize = importer.import("google oauth token client")

// TODO: pattern recognized! create a "google" object that does this for every service in the Google discovery list
var google = {drive: ({version, auth}) => getRpcFromSpec(require(path.join(__dirname, `../Resources/APIs/drive.${version}.json`)), auth)}

//var PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
/*
var credentials;
if(fs.existsSync('./sheet to web-8ca5784e0b05.json')) {
    credentials = path.resolve('./sheet to web-8ca5784e0b05.json');
} else {
    credentials = path.join(PROFILE_PATH, '.credentials/sheet to web-8ca5784e0b05.json');
}
*/

var GOOGLE_AUTH_SCOPE = [
    'https://www.googleapis.com/auth/drive'
];

async function listDriveFiles(drive, folder, pageToken) {
    var result = await drive.files.list({
        fields: 'files(kind,id,name,modifiedTime,md5Checksum,mimeType,owners,size,parents,originalFilename)',
        pageToken: pageToken,
        q: `'${folder}' in parents and trashed = false`
        //driveId: 'my-drive',
        //includeTeamDriveItems: true,
        //corpora: 'drive',
        //supportsAllDrives: true
    })
    if(result.data.nextPageToken) {
        var moreFiles = listDriveFiles(drive, folder, result.data.nextPageToken)
        return result.data.files.concat(moreFiles)
    } else {
        return result.data.files
    }
}

async function listDrive(folder = 'root') {
    var client = await authorize(GOOGLE_AUTH_SCOPE)
    var drive = await google.drive({version: 'v3', auth: client})
    var files = await listDriveFiles(drive, folder)
    return files
}

module.exports = listDrive

if(typeof $ != 'undefined') {
    listDrive()
        .then(r => $.sendResult(r))
        .catch(e => $.sendError(e))
}

What the code could have been:

const fs = require('fs');
const path = require('path');
const { GoogleAuth } = require('google-auth-library');
const { importAll } = require('../Core');
const getRpcFromSpec = importAll('../Core').import('get rpc from spec');
const authorize = importAll('../Core').import('google oauth token client');

// Refactored Google services object
const googleServices = {
  drive: (options) => getRpcFromSpec(require(path.join(__dirname, `../Resources/APIs/drive.${options.version}.json`)), options.auth),
};

// Refactored Google auth scope
const googleAuthScope = [
  'https://www.googleapis.com/auth/drive',
];

// Simplified and refactored listDriveFiles function
async function listDriveFiles(drive, folder, pageToken = null) {
  const options = {
    fields: 'files(kind,id,name,modifiedTime,md5Checksum,mimeType,owners,size,parents,originalFilename)',
    q: `'${folder}' in parents and trashed = false`,
  };
  if (pageToken) {
    options.pageToken = pageToken;
  }
  const result = await drive.files.list(options);
  if (result.data.nextPageToken) {
    return result.data.files.concat(await listDriveFiles(drive, folder, result.data.nextPageToken));
  }
  return result.data.files;
}

// Refactored listDrive function
async function listDrive(folder = 'root') {
  const client = await authorize(googleAuthScope);
  const drive = await googleServices.drive({ version: 'v3', auth: client });
  return listDriveFiles(drive, folder);
}

module.exports = listDrive;

if (typeof $!== 'undefined') {
  listDrive()
   .then((r) => $.sendResult(r))
   .catch((e) => $.sendError(e));
}

Code Breakdown

Importing Dependencies

The code starts by importing necessary dependencies:

var fs = require('fs');
var path = require('path');
var {GoogleAuth} = require('google-auth-library');
var importer = require('../Core')
var getRpcFromSpec = importer.import('get rpc from spec')
var authorize = importer.import('google oauth token client')

It then creates a google object to simplify access to Google APIs:

var google = {drive: ({version, auth}) => getRpcFromSpec(require(path.join(__dirname, `../Resources/APIs/drive.${version}.json`)), auth)}

Defining Constants and Functions

The code defines a constant for the Google authentication scope:

var GOOGLE_AUTH_SCOPE = [
    'https://www.googleapis.com/auth/drive'
];

It then defines two async functions:

listDriveFiles function

This function lists files in a specified Google Drive folder. It takes three parameters: drive (a Google Drive API client), folder (the ID of the folder to list), and pageToken (the current page token).

async function listDriveFiles(drive, folder, pageToken) {
   ...
}

listDrive function

This function lists files in the root folder of the user's Google Drive account. It takes an optional folder parameter (defaulting to 'root') and returns a list of files.

async function listDrive(folder = 'root') {
   ...
}

Exporting the listDrive function

The code exports the listDrive function:

module.exports = listDrive

Executing the listDrive function (Commented out)

The code includes a conditional statement to execute the listDrive function using a $.sendResult method, which is likely a part of a testing or debugging framework. This section is currently commented out:

if(typeof $!= 'undefined') {
    listDrive()
       .then(r => $.sendResult(r))
       .catch(e => $.sendError(e))
}