Help us understand the problem. What is going on with this article?

Github Apiを使って Issue Getter を作ってみた(with ajax request / jquery)

More than 1 year has passed since last update.

Github Apiを使って Issue Getter を作った

バンクーバーで受けたジュニアのフロントエンドエンジニア向けのテストの一部を公開!
とりあえず、CSSは全て無視して、機能だけを引っ張って来れるコードを書きました。

Frogのアドベントカレンダー向けに書きました。
https://adventar.org/calendars/2350

やったこと

  • レポジトリのURLを入力したら、Issueが全部出てくる
  • レーベルが現れる。
  • ClosedとOpenなIssueをタブで出し分ける
  • プルリクも別タブで見せる。
  • jquery Ajaxを使った

Github Apiって?

Githubが提供しているフリーなApiで,
公開されているGithubの中の情報全部を引っ張って来れるよ!

https://developer.github.com/v3/

ページ1: 検索ページ

Screen Shot 2017-12-12 at 12.22.00 PM.png

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0">
    <title>Github Issue Getter</title>
  </head>
  <body>
    <div class="page-search">
      <h1>GitHub Issue Getter</h1>
      <form action="issuelists.html" method="get">
        <input id="githubform" type="text" size="100" name="githubform" placeholder="レポジトリのリンクを貼ってね!">
      </form>
    </div>
    <script src="js/jquery-3.2.1.min.js"></script>
    <script src="js/script.js"></script>
  </body>
</html>

ページ2: 検索結果一覧

検索例) とりあえず、atomのリポジトリを引っ張ってみた。
https://github.com/atom/github

Screen Shot 2017-12-12 at 12.24.15 PM.png

issuelists.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0">
    <title>Issue 一覧</title>
  </head>
  <body>
    <header>
      <div>
        <h2>Issue 一覧</h2>
        <p></p>
      </div>
    </header>
    <div>
      <button onclick="window.location.href='index.html'">戻る</button>
      <div class="tabs">
          <button class="tablink btn-all-issues active" onclick="openTabs(event,'all-issues');">All Issues</button>
          <button class="tablink btn-open-issues" onclick="openTabs(event,'open-issues');">Open Issues</button></li>
          <button class="tablink btn-closed-issues" onclick="openTabs(event,'closed-issues');">Closed Issues</button>
          <button class="tablink btn-pull-requests" onclick="openTabs(event,'pull-requests');">Pull Requests</button>
      </div>
      <div class="tabcontent all-issues"></div>
      <div class="tabcontent open-issues"></div>
      <div class="tabcontent closed-issues"></div>
      <div class="tabcontent pull-requests"></div>
    </div>
    <script src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript">

      $(document).ready(function(){
          var url = window.location.href;
          var arg = url.split('?')[1].split('=')[1].split('%2F');

          var repos = arg[arg.length-1];
          var owner = arg[arg.length-2];

          var searchedHTML = "https://github.com/"+owner+"/"+repos

          $('.all-issues').html("");
          $.ajax(`https://api.github.com/repos/${owner}/${repos}/issues?state=all`,
          {
              dataType: 'json',
              timeout: 10000,
              success: function (data,status,xhr) {

                $('header p').html(searchedHTML);

                 $.each( data, function () {

                   var html = "";

                   var bodytext = "";

                   if (this.body === ""){
                     bodytext += "No description provided.";
                   } else{
                     bodytext = adjustTextSize(this.body);
                   }
                   var url = searchedHTML+"/issues/"+ this.number;

                   html += "<div>"+
                            "<h3><a href="+ url +">"+this.title+"</a></h3>"+
                            "<div>"+
                            "<p>"+ bodytext +"</p>"+
                            "<div>";

                  $.each(this.labels, function(){
                    html += "<div>"+this.name+"</div>";
                  });

                  html += "</div>"+"</div>"+"</div>";
                  $('.all-issues').append(html);

                  if (this.state == 'open') {
                    $('.open-issues').append(html);
                  }

                  if (this.state == 'closed') {
                    $('.closed-issues').append(html);
                  }
                });

              },
              error: function (jqXhr, textStatus, errorMessage) {
                  $('p').append('Error: ' + errorMessage);
              }
          });

            $.ajax(`https://api.github.com/repos/${owner}/${repos}/pulls`,
            {
              dataType: 'json',
              timeout: 20000,
              success: function (pulls,status,xhr) {

                $.each(pulls, function () {

                  var html = "";

                  var bodytext = adjustTextSize(this.body);
                  var url = searchedHTML +"/pull/"+ this.number;

                  html += "<div>"+
                           "<h3><a href="+url+">"+this.title+"</a></h3>"+
                           "<div>"+
                           "<p>"+ bodytext +"</p>"+
                           "<div>";

                 $.each(this.labels, function(){
                   html += "<div>"+this+"</div>";
                 });

                 html += "</div>"+"</div>"+"</div>";
                 $('.pull-requests').append(html);

               });

              },
                error: function (jqXhr, textStatus, errorMessage) { // error callback

                    $('.all-issues').html(' Error: ' + errorMessage+ '. Please check the url');
                }
            });

          function adjustTextSize(text){
            var txt = text;
            if (txt.length > 200) {
                return txt.substring(0, 200)+ '....';
            }
            return txt;
          }
        });
    </script>
  </body>
</html>

JSはこんな感じ(ほとんど2ページ目に書いてるけど)

script.js
function openTabs(evt, tabName){
      var i, tabcontent, tablinks;

      tabcontent = document.getElementsByClassName("tabcontent");
      for (i = 0; i < tabcontent.length; i++) {
          tabcontent[i].style.display = "none";
      }

      tablinks = document.getElementsByClassName("tablink");
      for (i = 0; i < tablinks.length; i++) {
          tablinks[i].className = tablinks[i].className.replace(" active", "");
      }

      document.getElementsByClassName(tabName)[0].style.display = "block";
      evt.currentTarget.className += " active";
}

$(document).ready(function(){

    $("#githubform").submit(function(submitEvent) {

    submitEvent.preventDefault();
    var url = $("#githubform").val();

    $.ajax(url,
    {
      dataType: 'json',
      timeout: 2000,
      success: function (data) {
        // console.log(data);
      }
    })
  });

});

あとはJQueryをダウンロードしてリンクすれば完成!

役になったらいいね!ください!

Saayaman
バイリンガル・デザイナー・フロントエンドです。 記事を英訳してます。Githubリンク載せてます。画像いっぱい載っけてます。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした