Github API返回另一个API端点以发出另一个请求

时间:2019-10-10 14:04:11

标签: reactjs github-api

我正在使用github的API来获取我的仓库的列表,然后过滤它们以显示一些指定的项目。我遇到的问题是某些数据是需要请求的另一个API端点。我以前从未遇到过。我想在从API返回第一个数据集后提出另一个获取请求吗?例如,我当前正在使用该特定终点

https://api.github.com/user/repos

这是我得到的一些数据

archive_url: "https://api.github.com/repos/myUserName/test-repo/{archive_format}{/ref}"
archived: false
assignees_url: "https://api.github.com/repos/myUserName/test-repo/assignees{/user}"
blobs_url: "https://api.github.com/repos/myUserName/test-repo/git/blobs{/sha}"
branches_url: "https://api.github.com/repos/myUserName/test-repo/branches{/branch}"
languages_url: "https://api.github.com/repos/alenart91/test-repo/languages"

所以现在,如果我想要angulars_url数据,我必须再次提出获取请求吗?

这是我当前的代码

import ProjectCard from './ProjectCard.js'

class Projects extends React.Component {
  constructor(props) {
    super(props);
    this.state = { projects: [], name: '' }
  }

  componentDidMount() {

    this.getProjects();
  }

  getProjects = () => {
   const token = 'private data';
   let url = 'https://api.github.com/user/repos';

   fetch(url , {
         mode: 'cors',
         headers: {
             'Accept': 'application/vnd.github.v3+json', 
             'Authorization': 'Bearer ' + token
         }})
         .then(res => {
           if (res.status === 200) {
             return res.json();
           } else {
             return res.statusText;
           }
         })
         .then( data => {

           let filteredProjects = data.filter( projectName => {
             return projectName.name == 'test-repo' || projectName.name == 'test-repo';
           })

           this.setState( {projects: filteredProjects });
         })
         .catch( err => {
           console.log(err);
         })

 }

  render() {

    const {projects} = this.state;
    return (
      <React.Fragment>

        {projects.map( projects => {
          return <ProjectCard language = {projects.language} description = {projects.description} url = {projects.html_url} name = {projects.name} />
        })}
      </React.Fragment>
    );
  }
}

export default Projects

1 个答案:

答案 0 :(得分:1)

是的,您需要对languages_url端点提出另一个获取请求。或者,您可以使用GraphQL在单个请求中获取存储库的语言。有关GraphQL调用,请参见下面的代码。参考GraphQL

{
  repository(owner: "<<OWNER>>", name: "<<REPONAME>>") {
    name
    languages(first: 10) {
      edges {
        node {
          name
        }
      }
    }
  }
}