首页 > 解决方案 > 从 GitHub 存储库获取文件信息的 GraphQL 查询

问题描述

我想在我的 Gatsby 站点中使用 GitHub 存储库来发布帖子。现在我正在使用两个查询,首先是获取文件的名称:

{
  viewer {
    repository(name: "repository-name") {
      object(expression: "master:") {
        id
        ... on Tree {
          entries {
            name
          }
        }
      }
      pushedAt
    }
  }
}

第二个是获取文件的内容:

{
  viewer {
    repository(name: "repository-name") {
      object(expression: "master:file.md") {
        ... on Blob {
          text
        }
      }
    }
  }
}

有什么方法可以获取有关每个文件何时创建和最后一次使用 GraphQL 更新的信息?现在我只能获取pushedAt整个存储库而不是单个文件。

标签: githubgraphqlgithub-api

解决方案


您可以使用以下查询来获取文件内容,同时获取该文件的最后一次提交。这样您还可以获得字段pushedAt,具体取决于您的需要committedDateauthorDate

{
  repository(owner: "torvalds", name: "linux") {
    content: object(expression: "master:Makefile") {
      ... on Blob {
        text
      }
    }
    info: ref(qualifiedName: "master") {
      target {
        ... on Commit {
          history(first: 1, path: "Makefile") {
            nodes {
              author {
                email
              }
              message
              pushedDate
              committedDate
              authoredDate
            }
            pageInfo {
              endCursor
            }
            totalCount
          }
        }
      }
    }
  }
}

请注意,我们还需要获取该endCursor字段才能获取文件的第一次提交(获取文件创建日期)

例如在Linux repo上,对于Makefile它提供的文件:

"pageInfo": {
  "endCursor": "b29482fde649c72441d5478a4ea2c52c56d97a5e 0"
}
"totalCount": 1806

所以这个文件有 1806 次提交

为了获得第一次提交,引用最后一个游标的查询将是b29482fde649c72441d5478a4ea2c52c56d97a5e 1804

{
  repository(owner: "torvalds", name: "linux") {
    info: ref(qualifiedName: "master") {
      target {
        ... on Commit {
          history(first: 1, after:"b29482fde649c72441d5478a4ea2c52c56d97a5e 1804", path: "Makefile") {
            nodes {
              author {
                email
              }
              message
              pushedDate
              committedDate
              authoredDate
            }
          }
        }
      }
    }
  }
}

它返回此文件的第一次提交。

我没有关于光标字符串格式的任何来源"b29482fde649c72441d5478a4ea2c52c56d97a5e 1804",我已经使用其他一些包含超过 1000 次提交的文件的存储库进行了测试,它似乎总是格式化为:

<static hash> <incremented_number>

如果有超过 100 个提交引用您的文件,则避免迭代所有提交

这是使用graphql.js的实现:

const graphql = require('graphql.js');

const token = "YOUR_TOKEN";
const queryVars = { name: "linux", owner: "torvalds" };
const file = "Makefile";
const branch = "master";

var graph = graphql("https://api.github.com/graphql", {
  headers: {
    "Authorization": `Bearer ${token}`,
    'User-Agent': 'My Application'
  },
  asJSON: true
});

graph(`
    query ($name: String!, $owner: String!){
      repository(owner: $owner, name: $name) {
        content: object(expression: "${branch}:${file}") {
          ... on Blob {
            text
          }
        }
        info: ref(qualifiedName: "${branch}") {
          target {
            ... on Commit {
              history(first: 1, path: "${file}") {
                nodes {
                  author {
                    email
                  }
                  message
                  pushedDate
                  committedDate
                  authoredDate
                }
                pageInfo {
                  endCursor
                }
                totalCount
              }
            }
          }
        }
      }
    }
`)(queryVars).then(function(response) {
  console.log(JSON.stringify(response, null, 2));
  var totalCount = response.repository.info.target.history.totalCount;
  if (totalCount > 1) {
    var cursorPrefix = response.repository.info.target.history.pageInfo.endCursor.split(" ")[0];
    var nextCursor = `${cursorPrefix} ${totalCount-2}`;
    console.log(`total count : ${totalCount}`);
    console.log(`cursorPrefix : ${cursorPrefix}`);
    console.log(`get element after cursor : ${nextCursor}`);

    graph(`
      query ($name: String!, $owner: String!){
        repository(owner: $owner, name: $name) {
          info: ref(qualifiedName: "${branch}") {
            target {
              ... on Commit {
                history(first: 1, after:"${nextCursor}", path: "${file}") {
                  nodes {
                    author {
                      email
                    }
                    message
                    pushedDate
                    committedDate
                    authoredDate
                  }
                }
              }
            }
          }
        }
      }`)(queryVars).then(function(response) {
        console.log("first commit info");
        console.log(JSON.stringify(response, null, 2));
      }).catch(function(error) {
        console.log(error);
      });
  }
}).catch(function(error) {
  console.log(error);
});

推荐阅读