Kyle Croft
Kyle Croft

Reputation: 5

Traverse through folder structure with Box API

I'm looking for guidance on the best way to traverse a folder structure via the Box API in JavaScript. I need to recursively loop though the structure based on the responses from the Box API and take action on returned files and folders.

When a folder is found I need to get all of it's containing items, and if that folder contains folders with items I need to get those as well, and so on and so forth. See example below:

StartingFolder
    Folder1A
        File1B
        Folder2B
            Folder1C
                File1D
            File2C
        Folder3B
        File4B
    Folder2A
        Folder1B
            File1C
        Folder2B
            Folder1C
                File1D
        File2B
    Folder3A
        File1B

All of these items are identified by an id and a type. So I know that if I find an item with type: "folder" then I need to make another request to Box to get its items using its id. I can easily do this on the first level but I don't know how to traverse the entire structure through to the bottom of each branch.

Any examples or best practices someone could provide would be great!

Upvotes: 0

Views: 1635

Answers (1)

John Hoerr
John Hoerr

Reputation: 8035

I don't have a JavaScript example but here's one in Python. Hopefully it'll give you some conceptual guidance on how to proceed.

def doSomethingWithFolder(folder):
    # Do something with the folder here

def recurse(folderId):
    # get the folder contents
    contents = client.folder(folder_id=folderId).get_items(limit=1000, offset=0)
    # filter the contents for just the subfolders based on the 'type' property
    folders = filter(lambda x: x.type=="folder", contents)
    # for each subfolder...
    for folder in folders:
        # ... take some action on the subfolder ...
        doSomethingWithFolder(folder)
        # ... and recurse using the 'id' property
        recurse(folder.id)         

recurse("0") # recurse starting from the root, or substitute another folder ID.

Upvotes: 2

Related Questions