Itererating all folders and files to get a list using js dropbox api

732 Views Asked by At

I need to get a list of all files by iterating all folders in the specified parent folder. I have heard that recursion is the best way to achieve, but I am unsure how to use recursion for fetching list of files in a folder using Dropbox API.

The below code works well for fetching the files in a single folder, I am looking to modify the code so it does a recursive fetch

<!doctype html>
<html>
<head>
  <title>Dropbox JavaScript SDK</title>
<style>
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  line-height: 1.5;
}
.container {
  display: block;
  width: 90%;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}
.container.main {
  padding-top: 30px;
}
code, .code {
  font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
  color: #666;
}
.info {
  font-size: 13px;
  font-style: italic;
  color: #666;
  margin-top: 40px;
}
a {
  color: #007ee5;
}
input {
  border: 2px solid #007ee5;
  border-radius: 3px;
  padding: 8px;
  font-size: 16px;
}
.button, button {
  border-radius: 3px;
  background-color: #007ee5;
  border: none;
  color: #fff;
  font-size: 16px;
  padding: 10px 15px;
  text-decoration: none;
}

.page-header {
  background-color: #007ee5;
  padding: 10px 0 0 0;
}
.page-header .container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 150px;
}
.page-header a {
  color: #fff;
  text-decoration: none;
}
.page-header nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.page-header h1 {
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 17px;
  font-weight: 200;
}
.page-header .logo {
  width: 100px;
  margin-right: 10px;
}
.page-header .view-source {
  font-weight: 200;
  font-size: 12px;
}
.page-header h2 {
  color: #fff;
  font-size: 18px;
  font-weight: normal;
}
</style>
  <script src="https://cdn.jsdelivr.net/npm/promise-polyfill@7/dist/polyfill.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropbox.js/10.27.0/Dropbox-sdk.min.js" integrity="sha512-nTLJySi/DUYzRvvxWOxf31QS5191sN1gpoq6EqGFHPFH0RlM6xOiY6jEp9dmwhDlyFmCmicwLOMnE+fUmo02KQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
  <!-- Example layout boilerplate -->
  <header class="page-header">
    <div class="container">
      <nav>
        <a href="/">
          <h1>
            <img src="https://cfl.dropboxstatic.com/static/images/brand/logotype_white-vflRG5Zd8.svg" class="logo" />
            JavaScript SDK Examples
          </h1>
        </a>
        <a href="https://github.com/dropbox/dropbox-sdk-js/tree/main/examples/javascript" class="view-source">View Source</a>
      </nav>
      <h2 class="code">
        <a href="/">examples</a> / basic
      </h2>
    </div>
  </header>

  <!-- Example description and UI -->
  <section class="container main">
    <p>This example fetches the contents of your root Dropbox directory. It uses the <code>Dropbox.filesListFolder()</code> method [<a href="http://dropbox.github.io/dropbox-sdk-js/Dropbox.html#filesListFolder">docs</a>].</p>

    <form id="basic-form" onSubmit="return listFiles()">
      <input type="text" id="access-token" placeholder="Access token" />
      <button type="submit">Submit</button>
    </form>

    <!-- The files returned from the SDK will be added here -->
    <ul id="files"></ul>

    <p class="info">To obtain an access token for quick testing, you can go to <a href="https://dropbox.github.io/dropbox-api-v2-explorer/#files_list_folder" target="_blank">API Explorer</a> click the "Get Token" button on the top right, copy the token it creates and then paste it here.</p>
  </section>

  <!-- Scripts to run example -->
  <script>
    var form = document.getElementById('basic-form');

    form.onsubmit = function listFiles(e) {
      e.preventDefault();

      var ACCESS_TOKEN = document.getElementById('access-token').value;
      var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
      dbx.filesListFolder({path: ''})
        .then(function(response) {
          console.log('response', response)
          displayFiles(response.result.entries);
        })
        .catch(function(error) {
          console.error(error);
        });
    }

    function displayFiles(files) {
      var filesList = document.getElementById('files');
      var li;
      for (var i = 0; i < files.length; i++) {
        li = document.createElement('li');
        li.appendChild(document.createTextNode(files[i][".tag"] + " " +  files[i].name));
        filesList.appendChild(li);
      }
    }
  </script>
</body>
</html>

1

There are 1 best solutions below

1
On

Quick attempt, non-tested code but you can use it as inspiration:

form.onsubmit = function listFiles(e) {
    e.preventDefault();

    var ACCESS_TOKEN = document.getElementById('access-token').value;
    var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
    var entries = {};
    let fetch_files = function(_path, entries){
        await dbx.filesListFolder({path: _path})
        .then(function(response) {
            console.log('response', response);
            entries = response.result.entries;
            for (var i = 0; i < entries.length; i++) {
                if(entries[i]['.tag'] == 'folder'){
                    entries[i]['subentries'] = {};
                    fetch_files(entries[i]['path_display'], entries[i]['subentries']);
                }
            }
        })
        .catch(function(error) {
            console.error(error);
        });
    };
    fetch_files('', entries);
    if(Object.keys(entries).length !== 0){
        displayFiles(entries);
    }
}

function displayFiles(files) {
    var filesList = document.getElementById('files');
    let append_list = function(arr, recursion){
        var li;
        for (var i = 0; i < arr.length; i++) {
            li = document.createElement('li');
            li.appendChild(document.createTextNode("&nbsp;".repeat(recursion * 4) + arr[i][".tag"] + " " +  arr[i].name));
            filesList.appendChild(li);
            if('subentries' in arr[i]){
                append_list(arr[i]['subentries'], recursion + 1);
            }
        }
    }
    append_list(files, 0)
}