Search code examples
javascriptgraphqlgithub-apigithub-graphql

How would I get the number of repositories for each user of an array?



I am trying to get the number of respositories of a few users using GitHub’s v4 API. In their explorer I found that I can query user(login: String!) however, that is only one users repositories count that I can see. Is it possible to loop though a list of users and get their each one of their repository counts using GitHub’s v4 API?


Solution

  • You can use aliases to add more user query to your request and build the graphql query programmatically looping through the user list. In the graphql explorer it would be something like this :

    {
      torvalds: user(login: "torvalds") {
        repositories() {
          totalCount
        }
      }
      nelenkov: user(login: "nelenkov") {
        repositories() {
          totalCount
        }
      }
      evilsocket: user(login: "evilsocket") {
        repositories() {
          totalCount
        }
      }
    }
    

    Try it in the explorer

    An example using graphql.js :

    var users = [ "torvalds", "nelenkov", "evilsocket"];
    
    var graph = graphql("https://api.github.com/graphql", {
      headers: {
        "Authorization": "Bearer YOUR_ACCESS_TOKEN"
      },
      asJSON: true
    });
    
    graph(`
      query {
        ${buildRepoCountFromUsers(users)}
      }
    `, {}).then(function(response) {
      console.log(response);
    }).catch(function(error) {
      console.log(error);
    });
    
    function buildRepoCountFromUsers(users){
      var query = "";
      for (var i = 0; i < users.length; i++){
        query+=` ${users[i]} : user(login: ${users[i]}) {
          repositories() {
            totalCount
          }
        }`;
      }
      return query;
    } 
    

    Note that I've chosen the user login as alias key here which works for the examples here but would not work if the login begins with a numeric character or if login contains hyphen. In that case you may use something like user0, user1 etc... and get the field login for each user