I want to get a list of things with get list (which I have already coded in), but next, I want a delete button that deletes all the things on that list. How can I do that with Google Drive SDK and Javascript?
Example, if my criteria is:
q: "starred = "+test+" and viewedByMeTime < '"+n+""
How do I delete every single file that meets that criteria?
References: https://developers.google.com/drive/v2/reference/files/delete https://developers.google.com/drive/v2/web/search-parameters
I tried fitting search file and delete files together, but I am really bad at it and I am not sure which variable represents all the files found matching the criteria and how to get that variable to be fileID:
function DeleteFiles() {
var x = document.getElementById("ResultShown").value;
var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0] ;
var test = false;
gapi.client.drive.files.list({
pageSize: x,
q: "starred = "+test+" and viewedByMeTime < '"+n+"'",
fields: "nextPageToken, files(id)",
}
).then(function deleteFile(fileId)) {
var request = gapi.client.drive.files.delete({
appendPre('Files:');
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
'fileId': fileId
});
request.execute(function(resp) { })
}
}
});
}
So using the Javascript Drive API, you will first issue a
GET
to the files endpoint, using thelist
action which supports your query parameterq
. It sounds like you already have that figured out.You will get a response object -- to get more specific, you would need to post some code. Are you using VanillaJS
XMLHttpRequest
, jQuery's$.ajax()
, perhaps the delicious and native asyncfetch()
API? Either way, you will get a response which can be parsed to JSON.As you have discovered, the Drive API does not support permanently deleting multiple Drive resources in one request. At this point, you may be rethinking the architecture of your application: removing a very long list could require many HTTP requests. This could generate significant overhead, so you might want to limit how long lists can be or do something else clever. If you decide to take this route, I'd suggest using
fetch
to use the API asynchronously.So after you call
JSON.parse(responseBody)
(orresponseBody.json()
if you're usingfetch()
), you will get something from Google API that looks like this:So what you need is:
A function which:
GET
to files.list is complete.responseJSON.items
and calls the function below with an itemId.A function which issues an
HTTP DELETE
given an ID.So without any specific details of your implementation, a general solution for your purpose might look like: