Class: SemaphoreCI::API::Client

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

Direct Known Subclasses

V1, V2

Instance Method Summary collapse

Constructor Details

#initialize(token, url, prefix, link_parser_class) ⇒ Client

Returns a new instance of Client.



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/semaphore_ci/api.rb', line 4

def initialize(token, url, prefix, link_parser_class)
  @token = token
  @url = url
  @prefix = prefix
  @link_parser = link_parser_class.new

  @conn = Faraday.new(url: @url) do |conn|
    # uncomment to enable Faraday debugging
    # conn.response :logger
    # conn.token_auth token # FIXME: make we work for V2 API
    conn.adapter :semaphore_net_http
  end
end

Instance Method Details

#get(path) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/semaphore_ci/api.rb', line 18

def get(path)
  response = @conn.get(path.prepend(@prefix), auth_token: @token)
  result = json_from(response)

  while (next_link = @link_parser.parse(response).by_rel('next'))
    response = @conn.get(next_link.target.to_s)
    next_result = json_from(response)

    case [result.class, next_result.class]
    when [Array, Array]
      # V2 pagination
      result.concat(next_result)
    when [Hash, Hash]
      # V1 pagination
      next_result.each do |key, value|
        if value.is_a? Array
          result[key].concat(value)
        elsif value.is_a? Hash
          result[key].merge(value)
        else
          result[key] = value
        end
      end
    else raise 'Unsupported API response'
    end
  end

  result
end