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

Github API v4にgraphql-client gemを使ってアクセスする

More than 1 year has passed since last update.

コード

あるレポジトリで所定のメンバーがあげて所定の日時以降にマージされたPRの一覧取得

source 'https://rubygems.org'

gem 'graphql-client' # 0.12.1
get_pull_requests.rb
#! /usr/bin/env ruby

require 'graphql/client'
require 'graphql/client/http'

h = GraphQL::Client::HTTP.new('https://api.github.com/graphql') do
  def headers(context)
    {
      "Authorization" => "Bearer #{ENV['ACCESS_TOKEN']}"
    }
  end
end
s = GraphQL::Client.load_schema(h)
c = GraphQL::Client.new(schema: s, execute: h)
Q = c.parse <<-GraphQL
query($after: String) {
  repository(owner:"our_company", name:"awesome_project") {
    pullRequests(first: 100, states: [MERGED], orderBy: {field: UPDATED_AT, direction: DESC}, after: $after) {
      edges {
        cursor
        node {
          number
          title
          updatedAt
          mergedAt
          author {
            login
          }
        }
      }
    }
  }
}
GraphQL

all_nodes = []
after = nil
loop do
  r = c.query(Q, variables: { after: after })
  nodes = r.data.repository.pull_requests.edges.map(&:node)
  nodes_in_time = nodes.select { |n| Time.parse(n.updated_at) > Time.new(2017, 10, 30) }
  all_nodes += nodes_in_time.select { |n| %w(alice bob carol).include?(n.author.login) }
  break if nodes.size > nodes_in_time.size
  after = r.data.repository.pull_requests.edges.last.cursor
end

puts all_nodes.map { |n| "##{n.number}\t#{n.author.login}\t#{n.merged_at}\t#{n.title}" }

雑多な解説

  • アクセストークンはPersonal access tokensのページで作れる
  • Qが定数なのはgraphql-clientの仕様で、queryメソッドに引数で渡すクエリ文字列が定数で無かった場合はエラーになる
  • orderByに何を指定したら良いかはドキュメントにはほとんど書かれていないがExplorerで適当に打つと補完されるのでわかる
  • 1回の取得件数が100件までなので、複数回に分けて取得する必要がある
  • edgeとnodeとcursorの仕組みはgraphQLではスタンダードとのこと
    • cursorを指定してここ以降を取得、とやることでデータを取得していく
  • 結果のオブジェクトはHashieよろしくメソッドで項目にアクセスできるが、元がmergedAtのようにcamelCaseであるものはmerge_atのようにsnake_caseのメソッド名になる
Why do not you register as a user and use Qiita more conveniently?
  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
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