How to Use Google Drive API to restore deleted data

Viewed 224

My Google Drive file was accidentally deleted by another subfolder owner, now I can see this file as an orphaned file but unable to identify the exact location and I want to restore the file structure of orphaned files. There is one option to restore file structure with the help of Google API, but I don't have sufficient knowledge about the API. I'd appreciate some assistance in the matter.

1 Answers

In order to restore a file and all its files, including files inside of subfolders (and so on) you can use the following code:

var FOLDER_TO_RESTORE_ID = 'YOUR_DELETED_FOLDER_ID';

function restoreFolder() {
  var root = DriveApp.getFolderById(FOLDER_TO_RESTORE_ID);
  var restoreq = [root];

  while (restoreq.length > 0) {
    var item = restoreq.pop();
    item.setTrashed(false);
    if (isFolder(item)) {
      var childFiles = item.getFiles();
      while (childFiles.hasNext()) {
        var file = childFiles.next();
        file.setTrashed(false);
      }
      var childFolders = item.getFolders();
      while (childFolders.hasNext()) {
        restoreq.push(childFolders.next());
      }
    }
  }
}

function isFolder(obj) {
  return Object.prototype.hasOwnProperty.call(obj, 'createFile');
}

You just have to replace YOUR_DELETED_FOLDER_ID for its appropriate value and execute it. This will visit the root folder (untrash it) and visit all its children (folders & files), recursively.

Related