Folder getParents fails to get Team Drive name in Google Script

*爱你&永不变心* 提交于 2019-12-01 13:28:42

Because Team Drives are implemented differently than "regular" Google Drive "folders", the built-in DriveApp is not guaranteed to work properly for all actions that deal with them. It is possible that at some point DriveApp will be updated to fully support Team Drives, but there are a lot of sensible things that Google still has yet to do ;)

Instead, use the "advanced service" Drive, which is a client application that implements version 2 of the Drive REST API, and allows properly handling Team Drive information. As an "advanced service", you must enable this service before you can use it.

To build the full path of a Team Drive item using only the advanced service:

function getTeamDrivePath(fileId) {
  // Declare we know how to handle Team Drive items, and that they be included in responses.
  var params = {
    supportsTeamDrives: true,
    includeTeamDriveItems: true
  };
  // Return only the fields we want, instead of the whole `File` resource.
  params.fields = "id,title,parents/id"

  // In a Team Drive, a file can have only one parent folder (e.g. "normal" filesystems).
  // (parent.isRoot is never true for Team Drive folders so it is not used.)
  var path = [], file;
  do {
    file = Drive.Files.get(fileId, params);
    path.unshift(file.title);
    fileId = file.parents.length ? file.parents[0].id : null;
  } while (fileId);

  // Since we also added the file, the last element of the path array is the filename.
  path.pop();

  // A Team Drive is subject to different permissions than files, and thus its name must be 
  // obtained via the Team Drives resource. Since `file` points to the Team Drive, use it:
  // Requesting incorrect fields will result in an API error, so request the proper ones:
  params.fields = "name"
  var td = Drive.Teamdrives.get(file.id, params);
  path[0] = td.name;
  return path;
}

More reading about Team Drives and handling associated with them is available on the Drive REST API reference. I link the v2 versions since they are what is available via Apps Script's "Advanced Service", but the v3 version should be used for 3rd party applications using the client libraries.

Important resources:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!