Monday, 29 May 2017

Google Node API as Promise for File List

As disclosure I am very new to Node.

Basically I want to recurse through a Google Docs folder and pull out an array of docs files within any amount of folders. The following is one mf many attempts - including trying to integrate Promise.all amongst others.

My issue here is knowing where to place the promise - collect the promises from the recursion and spit out the promise collection after all has been collected.

My console outputs the fileList before any files have been found - this leads me to believing that the response.files.forEach((file) should be promisfied in some fashion but how I am unsure.

Any help appreciated

static getFiles () {
// Create Promise
return new Promise((resolve, reject) => {
  // Get time
  const time = this._getTimeFile()
  const googleFolder = this.getFolder()

  // Debug
  Log.info('GoogleDrive - getFiles - folder - time:', googleFolder, time)

  // Options
  const options = {
    auth: this.jwtClient,
    pageSize: 1000,
    fields: 'nextPageToken, files( id, name, mimeType, createdTime, modifiedTime )',
    orderBy: 'modifiedTime desc',
    q: `trashed != true and (mimeType='application/vnd.google-apps.folder' or (mimeType='application/vnd.google-apps.document' and modifiedTime > '${time}')) and '${googleFolder}' in parents`,
    spaces: 'drive'
  }

  let fileList = []

  // Drive list
  drive.files.list(
    options
  , (error, response) => {
    // Catch an error
    if (error) {
      // Debug
      Log.error('GoogleDrive - getFiles - Probably issue with the Query:', error)

      // Return
      reject(new Error(error))
    }

    // Check for no files returned
    if (response.files.length === 0) {
      // Debug
      Log.warn('GoogleDrive - getFiles - No files found:', response)

      // // Return
      // return reject(new Error(response))

    // Process files or folder found
    } else {
      // Debug
      // Log.info('Get Files:', response.files)

      // Loop through the response
      response.files.forEach((file) => {
        // Check for a Folder type
        if (file.mimeType === 'application/vnd.google-apps.folder') {
          // Set new folder and loop the folders
          this.setFolder(file.id).getFiles()
          .then((data) => {
            // Debug
            Log.info('GoogleDrive - getFiles: - Folder:', file.name)
            resolve()
          })

        // listFile( folder, "#{domain}/#{file.name}", file.id, file.name )
        } else {
          Log.info('GoogleDrive - getFiles: - File:', file.name)

          // Collect the list of files
          fileList.push({ name: file.name })
        }
      })

      Log.info('GoogleDrive - getFiles - fileList', fileList)

      // Return
      resolve(fileList)
    }
  })
})

}



via Ian Warner

No comments:

Post a Comment