Как исправить предупреждение «В теле ресурса есть поля, которые не доступны для записи» из Google Drive API? - PullRequest
0 голосов
/ 12 февраля 2019

Я использую пример из Google API Docs v3 (Это живой пример, чтобы увидеть ошибку).При попытке обновить разрешение файла появляется следующая ошибка:

Тело ресурса содержит поля, которые не доступны для прямой записи.

Разрешение файла необходимо обновить доразрешить доступ к URL для всех, поэтому мы можем использовать «загруженный» файл в качестве инструмента для обмена.Если вы удалите опцию ' type ', скрипт запустится.Прочтите другие вопросы по этому поводу, включая this , но не помогли решить эту проблему.В целом, цель состоит в том, чтобы сделать файл, который пользователь выбирает в палитре Google, доступным для совместного использования.Любые указатели были бы великолепны.

Код ниже (такой же, как URL выше).

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for drive.permissions.update
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/guides/code_samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/drive/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.drive.permissions.update({
      "fileId": "xxxxxx",
      "permissionId": "xxxxxx",
      "removeExpiration": false,
      "supportsTeamDrives": true,
      "transferOwnership": true,
      "resource": {
        "type": "anyone",
        "role": "owner"
      }
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: YOUR_CLIENT_ID});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

Подводя итог, я попытался обновить роль / тип пользователя с помощью приведенного ниже, но даже при отсутствии ошибок,текущие поля не обновляются.

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for drive.permissions.list
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/guides/code_samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.photos.readonly https://www.googleapis.com/auth/drive.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/drive/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.





function updatePermission(fileId, permissionId, newRole) {
  var newRole = "owner";
  // First retrieve the permission from the API.
  var request = gapi.client.drive.permissions.get({
    "fileId": "xxxxx",
    'permissionId': "xxxxx",
  });

  request.execute(function(resp) {
    resp.role = newRole;
    var updateRequest = gapi.client.drive.permissions.update({
      'fileId': "xxxxx",
      'permissionId': "xxxxx",
      'resource': resp
    });
    updateRequest.execute(function(resp) {
    });
  });
}



  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "xxx"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="updatePermission()">execute</button>

Теперь он работает, но фактически не обновляет информацию, когда вы проверяете ее по this

1 Ответ

0 голосов
/ 12 февраля 2019

Если вы проверяете документацию на разрешение обновления тело сообщения.Вы заметите, что доступны только два поля для записи

enter image description here

Вы пытаетесь обновить некоторые столбцы, которые недоступны для записи.

  "removeExpiration": false,
  "supportsTeamDrives": true,
  "transferOwnership": true,

Попробуйте сделать:

 /**
 * Update a permission's role.
 *
 * @param {String} fileId ID of the file to update permission for.
 * @param {String} permissionId ID of the permission to update.
 * @param {String} newRole The value "owner", "writer" or "reader".
 */
function updatePermission(fileId, permissionId, newRole) {
  // First retrieve the permission from the API.
  var request = gapi.client.drive.permissions.get({
    'fileId': fileId,
    'permissionId': permissionId
  });
  request.execute(function(resp) {
    resp.role = newRole;
    var updateRequest = gapi.client.drive.permissions.update({
      'fileId': fileId,
      'permissionId': permissionId,
      'resource': resp
    });
    updateRequest.execute(function(resp) { });
  });
}
...