Search code examples
dropboxdropbox-api

Checking file existence (Dropbox API v2)


I am working on a project with the following technology stack: Angular, Ionic, Cordova. When downloading a file into Dropbox, I need to check whether it is on the disk or not. If the file already exists on disk, I need to rename it. I use (https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata) to verify the existence of a file. The logic is this, if this method returns an error, then there is no such file and I upload it. If the method returns metadata, the file must be renamed. With this approach, a request to the console will throw an error (this is natural). Is there an alternative to such an approach that would not give an error to the console? This is a piece of code that implements this approach.

  async getNewFileName(fileName: string): Promise<string> {
    const { name, extension } = getNameExtension(fileName);
    for (let i = 0;; i++) {
      const tmpName = i ? `${name}(${i}).${extension}` : fileName;
      if (!await this.checkDropBoxFile(tmpName)) {
        return tmpName;
      }
    }
    return fileName;
  }

  async checkDropBoxFile(fileName: string): Promise<any> {
    const dbx = this.getDropbox();
    try {
      const res = await dbx.filesGetMetadata({ path: '/' + fileName });
      return res;
    } catch (e) {
      return false;
    }
  }

Solution

  • Instead of calling /files/get_metadata on each file name to check whether it exists, you could use the /files/list_folder endpoint to list all contents of the folder and then iterate over the results to check file names. That would get rid of the error and, depending on how your app is structured, may result in fewer calls to the Dropbox API.
    You can play around with the /files/list_folder endpoint (and others) in the Dropbox API explorer.