How do I delete a list of files meeting criteria w

2019-09-13 04:35发布

问题:

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) { })
        }
      } 
    });
  }

回答1:

So using the Javascript Drive API, you will first issue a GET to the files endpoint, using the list action which supports your query parameter q. 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 async fetch() 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) (or responseBody.json() if you're using fetch()), you will get something from Google API that looks like this:

{
 "kind": "drive#fileList",
 "etag": "...",
 "selfLink": "https://www.googleapis.com/drive/v2/files",
 "nextPageToken": "...",
 "nextLink": "...",
 "incompleteSearch": false,
 "items": [
  {
   "kind": "drive#file",
   "id": "SOME FILE ID",
   "etag": "...",
   "selfLink": "...",
   "alternateLink": "...",
   "embedLink": "...",
   "openWithLinks": {
        ...
   },
   {
   "kind": "drive#file",
   "id": "SOME FILE ID",
   "etag": "...",
   "selfLink": "...",
   "alternateLink": "...",
   "embedLink": "...",
   "openWithLinks": {
        ...
   }
]

So what you need is:

  1. A function which:

    • Is called when your GET to files.list is complete.
    • Loops through responseJSON.items and calls the function below with an itemId.
  2. 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:

var apiEndpoint = new URL("https://www.googleapis.com/drive/v2/files"),
    params = {q: "some stuff", otherParams: "lol"}

// assemble GET querystring in a nice way
Object.keys(params).forEach(function(key) {
   apiEndpoint.searchParams.append(key, params[key]);
});

// go and fetch! (explicit HTTP header options optional but good practice)
fetch(apiEndpoint , {
                 method: 'GET',
                 mode: 'cors',
                 redirect: 'follow',
                 headers: new Headers({
                     'Content-Type': 'application/json'
                 })
             });
                 .then(function (responseBody) {
                     return responseBody.json();
                 })
                 .then(function (responseObj) {
                     for(i=0; i<responseObj.items.length; i++) {
                         asyncDeleteDriveItem(responseObj.items[i].id);
                     }
                 });

        });

function asyncDeleteDriveItem() {/* ... */}