Class: Asimov::ApiV1::Base

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
HTTParty
Defined in:
lib/asimov/api_v1/base.rb

Overview

Base class for API interface implementations. Currently manages the network logic for the interface.

Instance Method Summary collapse

Constructor Details

#initialize(client: nil) ⇒ Base

Returns a new instance of Base.



16
17
18
# File 'lib/asimov/api_v1/base.rb', line 16

def initialize(client: nil)
  @client = client
end

Instance Method Details

#check_for_api_error(resp) ⇒ Object



83
84
85
86
87
88
# File 'lib/asimov/api_v1/base.rb', line 83

def check_for_api_error(resp)
  return if resp.code == 200

  ApiErrorTranslator.translate(resp)
  resp
end

#http_delete(path:) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/asimov/api_v1/base.rb', line 21

def http_delete(path:)
  wrap_response_with_error_handling do
    self.class.delete(
      path,
      { headers: headers }.merge!(request_options)
    )
  end
end

#http_get(path:) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/asimov/api_v1/base.rb', line 30

def http_get(path:)
  wrap_response_with_error_handling do
    self.class.get(
      path,
      { headers: headers }.merge!(request_options)
    )
  end
end

#http_streamed_download(path:, writer:) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/asimov/api_v1/base.rb', line 59

def http_streamed_download(path:, writer:)
  self.class.get(path,
                 { headers: headers,
                   stream_body: true }.merge!(request_options)) do |fragment|
    fragment.code == 200 ? writer.write(fragment) : check_for_api_error(fragment)
  end
rescue Asimov::RequestError => e
  # Raise any translated API errors
  raise e
rescue StandardError => e
  # Otherwise translate the error to a network error
  NetworkErrorTranslator.translate(e)
end

#json_post(path:, parameters:) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/asimov/api_v1/base.rb', line 39

def json_post(path:, parameters:)
  wrap_response_with_error_handling do
    self.class.post(
      path,
      { headers: headers,
        body: parameters&.to_json }.merge!(request_options)
    )
  end
end

#multipart_post(path:, parameters: nil) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/asimov/api_v1/base.rb', line 49

def multipart_post(path:, parameters: nil)
  wrap_response_with_error_handling do
    self.class.post(
      path,
      { headers: headers("multipart/form-data"),
        body: parameters }.merge!(request_options)
    )
  end
end

#wrap_response_with_error_handlingObject



73
74
75
76
77
78
79
80
81
# File 'lib/asimov/api_v1/base.rb', line 73

def wrap_response_with_error_handling
  resp = begin
    yield
  rescue StandardError => e
    NetworkErrorTranslator.translate(e)
  end
  check_for_api_error(resp)
  resp.parsed_response
end