Class: FractalApi::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/fractal_api/client.rb

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



11
12
13
# File 'lib/fractal_api/client.rb', line 11

def initialize
  Faraday::Request.register_middleware fractal_api_auth: -> { FractalApi::FaradayAuth }
end

Instance Method Details

#api_urlObject



44
45
46
# File 'lib/fractal_api/client.rb', line 44

def api_url
  FractalApi.configuration.base_url
end

#connectionObject



33
34
35
36
37
38
39
40
41
42
# File 'lib/fractal_api/client.rb', line 33

def connection
  @connection ||= Faraday.new(url: api_url) do |conn|
    conn.request :fractal_api_auth,
                 FractalApi.configuration.api_key,
                 FractalApi.configuration.partner_id
    conn.response :json, parser_options: { symbolize_names: true }
    conn.response :logger if FractalApi.configuration.debug
    conn.adapter Faraday.default_adapter
  end
end

#get(path, params: {}, headers: {}) ⇒ Object



15
16
17
18
19
# File 'lib/fractal_api/client.rb', line 15

def get(path, params: {}, headers: {})
  connection.get(path, params, headers).tap do |response|
    handle_response(response)
  end
end

#handle_response(response) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/fractal_api/client.rb', line 48

def handle_response(response)
  return if response.success?

  case response.status
  when 400
    raise InvalidRequestError, response.body.inspect
  when 401
    raise APIKeyError, response.body.inspect
  when 403
    raise UnauthorizedError, response.body.inspect
  when 404
    raise NotFoundError, response.body.inspect
  else
    raise GenericError, "#{response.status}: #{response.body.inspect}"
  end
end

#post(path, params: {}, headers: {}) ⇒ Object



21
22
23
24
25
# File 'lib/fractal_api/client.rb', line 21

def post(path, params: {}, headers: {})
  connection.post(path, MultiJson.dump(params), headers).tap do |response|
    handle_response(response)
  end
end

#put(path, params: {}, headers: {}) ⇒ Object



27
28
29
30
31
# File 'lib/fractal_api/client.rb', line 27

def put(path, params: {}, headers: {})
  connection.put(path, MultiJson.dump(params), headers).tap do |response|
    handle_response(response)
  end
end