对于大小超过 ~1MB 的文件,来自 Github.js getSha 的 403 错误

Nic*_*dez 5 javascript github github-api http-status-code-403 github.js

当我尝试使用Github.js从大于 ~1MB 的文件中 getSha(以及随后的 getBlob)时,出现 403 错误。文件大小有限制吗?代码如下:

var gh = new GitHub({
    username: username,
    password: password
});

// get the repo from github
var repo = gh.getRepo('some-username','name-of-repo');

// get promise
repo.getSha('some-branch', 'some-file.json').then(function(result){

  // pass the sha onto getBlob
  return repo.getBlob(result.data.sha);

}).then(function(result){

  do_something_with_blob(result.data);

});
Run Code Online (Sandbox Code Playgroud)

GitHub API 表示它支持最大 100MB 的 blob,但我在Github.js 文档中找不到任何有关文件大小限制的信息。此外,这些文件来自私人 Github 存储库。

Ber*_*tel 3

它会抛出403 Forbidden错误,因为它使用Github GET 内容 API,该 API 给出的文件结果不超过 1Mo。例如以下将抛出 403 :

https://api.github.com/repos/bertrandmartel/w230st-osx/contents/CLOVER/tools/Shell64.efi?ref=master

使用此方法使用 GET tree API,您可以获取文件 sha,而无需下载整个文件然后使用(对于不超过 100Mo 的文件repo.getBlob使用Get blob API )。

以下示例将使用 GET trees api 获取指定文件(对于超过 1Mo 的文件)的父文件夹的树,按名称过滤特定文件,然后请求 blob 数据:

const accessToken = 'YOUR_ACCESS_TOKEN';

const gh = new GitHub({
  token: accessToken
});

const username = 'bertrandmartel';
const repoName = 'w230st-osx';
const branchName = 'master';
const filePath = 'CLOVER/tools/Shell64.efi'

var fileName = filePath.split(/(\\|\/)/g).pop();
var fileParent = filePath.substr(0, filePath.lastIndexOf("/"));

var repo = gh.getRepo(username, repoName);

fetch('https://api.github.com/repos/' +
  username + '/' +
  repoName + '/git/trees/' +
  encodeURI(branchName + ':' + fileParent), {
    headers: {
      "Authorization": "token " + accessToken
    }
  }).then(function(response) {
  return response.json();
}).then(function(content) {
  var file = content.tree.filter(entry => entry.path === fileName);

  if (file.length > 0) {
    console.log("get blob for sha " + file[0].sha);
    //now get the blob
    repo.getBlob(file[0].sha).then(function(response) {
      console.log("response size : " + response.data.length);
    });
  } else {
    console.log("file " + fileName + " not found");
  }
});
Run Code Online (Sandbox Code Playgroud)