Class: Github::Client

Inherits:
Object
  • Object
show all
Includes:
Checks
Defined in:
app/github/client.rb

Overview

It’s a GitHub client. I know there is an official client library.

Instance Method Summary collapse

Methods included from Checks

#check_boolean, #check_enumerable_of, #check_is_a, #check_non_empty_string, #check_non_nil, #check_positive_integer

Constructor Details

#initialize(access_token:, logger: Logger.new($stdout)) ⇒ Client

Returns a new instance of Client.



15
16
17
18
# File 'app/github/client.rb', line 15

def initialize(access_token:, logger: Logger.new($stdout))
  @access_token = check_non_empty_string(access_token: access_token)
  @logger = check_non_nil(logger: logger)
end

Instance Method Details

#get(url) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/github/client.rb', line 20

def get(url)
  check_non_empty_string(url: url)

  @logger.info "#{self.class} GET #{url}"
  response = RestClient.get(
    url,
    {
      'Accept' => 'application/vnd.github+json',
      'Authorization' => "Bearer #{@access_token}",
      'X-GitHub-Api-Version' => '2022-11-28'
    }
  )

  raise "GET #{url} returned #{response.code}, expected 200: #{response}" unless response.code == 200

  JSON.parse(response)
rescue RestClient::RequestFailed => e
  @logger.error("#{self.class} GET #{url} failed: #{e.response.code} #{e.response}")
  raise e
end

#post(url, request) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/github/client.rb', line 41

def post(url, request)
  check_non_empty_string(url: url)
  check_is_a(request: [Hash, request])

  @logger.info "#{self.class} POST #{url}"
  response = RestClient.post(
    url,
    request.to_json,
    {
      'Accept' => 'application/vnd.github+json',
      'Authorization' => "Bearer #{@access_token}",
      'X-GitHub-Api-Version' => '2022-11-28'
    }
  )
  raise "POST #{url} failed: #{response.code} #{response}" unless response.code == 201

  JSON.parse(response)
rescue RestClient::RequestFailed => e
  @logger.error("#{self.class} POST #{url} failed: #{e.response.code} #{e.response}")
  raise e
end