Class: Underway::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/underway/api.rb

Class Method Summary collapse

Class Method Details

.debug_octokit!Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/underway/api.rb', line 67

def self.debug_octokit!
  stack = Faraday::RackBuilder.new do |builder|
    builder.use Octokit::Middleware::FollowRedirects
    builder.use Octokit::Response::RaiseError
    builder.use Octokit::Response::FeedParser
    builder.response :logger
    builder.adapter Faraday.default_adapter
  end
  Octokit.middleware = stack
end

.generate_jwtObject



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/underway/api.rb', line 31

def self.generate_jwt
  payload = {
    # Issued at time:
    iat: Time.now.to_i,
    # JWT expiration time (10 minute maximum)
    exp: Time.now.to_i + (10 * 60),
    # GitHub Apps identifier
    iss: Underway::Settings.config.app_issuer
  }

  JWT.encode(payload, Underway::Settings.config.private_key, "RS256")
end

.installation_token(id:) ⇒ Object

Returns a valid auth token for the installation



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/underway/api.rb', line 45

def self.installation_token(id:)
  if token = Underway::Settings.config.token_cache.lookup_installation_auth_token(id: id)
    log("token cache: hit")
    return token
  else
    log("token cache: miss")
    res = invoke(
      "/app/installations/#{id}/access_tokens",
      method: :post
    )

    if error = res[:error]
      raise ArgumentError.new(error)
    end

    token = res.token
    expires_at = res.expires_at.to_s
    Underway::Settings.config.token_cache.store_installation_auth_token(id: id, token: token, expires_at: expires_at)
    token
  end
end

.invoke(route, headers: {}, method: :get) ⇒ Object

Returns a Sawyer::Resource or PORO from the GitHub REST API



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/underway/api.rb', line 7

def self.invoke(route, headers: {}, method: :get)
  debug_octokit! if verbose_logging?

  Octokit.api_endpoint = Underway::Settings.config.raw["github_api_host"]

  if !headers[:authorization] && !headers["Authorization"]
    Octokit.bearer_token = generate_jwt
  end

  final_headers = {
    accept: "application/vnd.github.machine-man-preview+json",
    headers: headers
  }

  begin
    case method
    when :post then Octokit.post(route, final_headers)
    else Octokit.get(route, final_headers)
    end
  rescue Octokit::Error => e
    { error: e.to_s }
  end
end

.verbose_logging?Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/underway/api.rb', line 78

def self.verbose_logging?
  !!Underway::Settings.config.verbose_logging
end