index.js
Home
/
index.js
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 rootFolders = []
const getFolders = 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 folderIds = []
for (let i = 0; i <= iterations; i++) {
let items = await client.folders.get(id, {limit: chunks, offset: (chunks * i)})
let parts = items.item_collection.entries.filter(f => f.type === 'folder').map(f => f.id)
folderIds.push(...parts)
}
if (folderIds.length === 0) {
rootFolders.push(id)
return
} else {
for (let folderId of folderIds) {
await getFolders(folderId)
}
}
}
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: (chunks * 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) => {
await getFolders(parentFolder)
const folderIds = [...rootFolders]
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)
}
})()