I just finished a simple script for Node that will delete all the folders and files inside a specified folder ID through Box's API. It works by getting a list of items inside a folder, then generating a list of File IDs and Folder IDs, then making parallel calls to Box's delete file and delete folder endpoints.
This script is currently working, it'll delete everything inside a folder I specified. However, I'm not confident about my understandings in regards to Promises, as well as dealing with the response returned from an API call.
Can you please give me some feedback on the way I'm using async
/await
, promises, and the way I'm mapping certain arrays? perhaps make it more elegant and follow best practices?
Things to do:
- Refactor
Axios
auth header andbaseUrl
into config to reduce repeated code
Few Questions I have:
- On line 78, why don't I need to use
.then()
after.all()
? A: found the answer,await
replaces.then()
- Is there a way to combine line 78 & line 79 into one statement?
- Am I using
async/await
properly and following best practices? - My javascript is kind of rusty, my background is mostly C#, are there any structural changes I should make to the whole script?
const axios = require('axios');
const BOX_TOKEN = '1111';
const DOC_FOLDERID = '1111';
(async function() {
let allItems = await getAllFolderItems();
let filteredItems = await filterItems(allItems);
deleteFiles(filteredItems[0]);
deleteFolders(filteredItems[1]);
})();
async function getFolderItems(folderId, nextMarker) {
let limit = 1;
let responseData = await axios({
method: 'get',
url: `https://api.box.com/2.0/folders/${folderId}/items?fields=id,name,content_created_at,type&limit=${limit}&usemarker=true&marker=${nextMarker}`,
headers: {'Authorization': `Bearer ${BOX_TOKEN}`}
})
.then(response => { return response.data })
.catch(error => { return error });
return responseData;
}
async function getAllFolderItems() {
let allItems = [], keepGoing = true, nextMarker = '';
// Recursive call to get all the items in a large folder
while(keepGoing) {
let folderItems = await getFolderItems(DOC_FOLDERID, nextMarker);
if (folderItems.entries)
allItems.push(...folderItems.entries);
if (folderItems.next_marker != '' && folderItems.next_marker != undefined) {
nextMarker = folderItems.next_marker;
keepGoing = true;
} else
keepGoing = false;
}
console.log(allItems);
return allItems;
}
async function filterItems(allItems) {
let folderIDsToDelete = {}, fileIDsToDelete = {};
// Compile a list of folders and list of files if they are older than 1 day
// Goal is to only delete items that are more than 1 day old
for (let i = 0; i < allItems.length; i++) {
let oneDayAgo = new Date().getTime() - (1 * 24 * 60 * 60 * 1000);
let itemDate = new Date(allItems[i].content_created_at);
if (oneDayAgo > itemDate) {
if (allItems[i].type === 'file')
fileIDsToDelete[allItems[i].id] = allItems[i].content_created_at;
else
folderIDsToDelete[allItems[i].id] = allItems[i].content_created_at;
}
}
console.log('Files to Delete ', fileIDsToDelete);
console.log('Folders to Delete ', folderIDsToDelete);
return [fileIDsToDelete, folderIDsToDelete];
}
async function deleteFiles(fileIDsToDelete) {
let baseUrl = 'https://api.box.com/2.0/files/';
let requestUrls = Object.keys(fileIDsToDelete).map(key => baseUrl + key);
console.log(requestUrls);
var promises = [];
for (let request of requestUrls) {
promises.push(axios.delete(request, {
headers: {'Authorization': `Bearer ${BOX_TOKEN}`}
}));
}
try {
var responses = await axios.all(promises);
var responseStatuses = responses.map(responses => responses.status);
console.log(responseStatuses);
} catch (error) {
console.log(error);
}
}
async function deleteFolders(folderIDsToDelete) {
let baseUrl = 'https://api.box.com/2.0/folders/';
let queryParam = '?recursive=true';
let requestUrls = Object.keys(folderIDsToDelete).map(key => baseUrl + key + queryParam);
console.log(requestUrls);
var promises = [];
for (let request of requestUrls) {
promises.push(axios.delete(request, {
headers: {'Authorization': `Bearer ${BOX_TOKEN}`}
}));
}
try {
var responses = await axios.all(promises);
var responseStatuses = responses.map(responses => responses.status);
console.log(responseStatuses);
} catch (error) {
console.log(error);
}
}