index.js

60 lines | 1.923 kB Blame History Raw Download
require('dotenv').config()
const BoxSDK = require('box-node-sdk')
const path = require('path')
const util = require('util')
const writeFile = util.promisify(require('fs').writeFile)

// Initialize the SDK with your app credentials
const sdk = new BoxSDK({
  clientID: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET
});

// Create a basic API client, which does not automatically refresh the access token
const client = sdk.getBasicClient(process.env.DEV_TOKEN);

const getChildFolders = async (id) => {
  const r = await client.folders.get(id)
  const folderIds = r.item_collection.entries.filter(f => f.type === 'folder').map(f => f.id)
  return folderIds
}

const getFolderContents = async (id) => {
  const r = await client.folders.get(id, {limit: 1})
  const chunks = 100
  const iterations = Math.floor(r.item_collection.total_count / chunks)
  const files = []
  for (let i = 0; i <= iterations; i++) {
    let items = await client.folders.get(id, {limit: chunks, offset: i})
    let parts = items.item_collection.entries.filter(f => f.type === 'file').map(f => { return [f.name.split('.')[0], f.id, f.name, `${process.env.PUBLIC_URL}${f.id}`] })
    files.push(...parts)
    console.log(id, i, '/', iterations)
  }
  return files
}

const main = async (parentFolder) => {
  const folderIds = await getChildFolders(parentFolder)
  const files = []
  for (let folderId of folderIds) {
    let contents = await getFolderContents(folderId)
    files.push(...contents)
  }
  const outF = path.resolve(__dirname, `./output/${parentFolder}.csv`)
  await writeFile(outF, 'grid,id,name,link\n', {flag: 'a'})
  for (let file of files) {
    let line = file.join(',')
    await writeFile(outF, `${line}\n`, {flag: 'a'})
  }
}

(async () => {
  try {
    // parentFolder is top level folder ID to inspect
    const parentFolder = process.env.PARENT_FOLDER
    await main(parentFolder)
    console.log('DONE!')
  } catch (e) {
    console.error(e)
  } 
})()