Module: ExternalServices::Api
- Defined in:
- lib/external_services/api.rb
Defined Under Namespace
Classes: Error
Instance Method Summary collapse
- #api_key ⇒ Object
- #api_url ⇒ Object
- #auth_header ⇒ Object
- #connection ⇒ Object
- #delete(path, params: {}, **_kwargs) ⇒ Object
- #fake? ⇒ Boolean
- #fake_response_body(method, _path, _params = {}) ⇒ Object
- #get(path, params: {}, **_kwargs) ⇒ Object
- #post(path, body:, params: {}, **_kwargs) ⇒ Object
- #put(path, body:, params: {}, **_kwargs) ⇒ Object
- #request(method, path, params = {}, body = nil) ⇒ Object
Instance Method Details
#api_key ⇒ Object
28 29 30 |
# File 'lib/external_services/api.rb', line 28 def api_key ENV["#{to_s.demodulize.upcase}_API_KEY"] end |
#api_url ⇒ Object
24 25 26 |
# File 'lib/external_services/api.rb', line 24 def api_url ENV["#{to_s.demodulize.upcase}_API_URL"] end |
#auth_header ⇒ Object
32 33 34 |
# File 'lib/external_services/api.rb', line 32 def auth_header 'Authorization' end |
#connection ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/external_services/api.rb', line 36 def connection return if api_url.blank? @connection ||= Faraday.new(url: api_url) do |f| f.request :json f.response :json f.adapter :net_http f.headers['Content-Type'] = 'application/json' f.headers['Accept'] = 'application/json' f.headers[auth_header] = api_key end end |
#delete(path, params: {}, **_kwargs) ⇒ Object
63 64 65 |
# File 'lib/external_services/api.rb', line 63 def delete(path, params: {}, **_kwargs) request(:delete, path, params) end |
#fake? ⇒ Boolean
67 68 69 |
# File 'lib/external_services/api.rb', line 67 def fake? !connection end |
#fake_response_body(method, _path, _params = {}) ⇒ Object
71 72 73 |
# File 'lib/external_services/api.rb', line 71 def fake_response_body(method, _path, _params = {}) (method == :post ? { 'id' => SecureRandom.hex } : {}) end |
#get(path, params: {}, **_kwargs) ⇒ Object
51 52 53 |
# File 'lib/external_services/api.rb', line 51 def get(path, params: {}, **_kwargs) request(:get, path, params) end |
#post(path, body:, params: {}, **_kwargs) ⇒ Object
55 56 57 |
# File 'lib/external_services/api.rb', line 55 def post(path, body:, params: {}, **_kwargs) request(:post, path, params, body) end |
#put(path, body:, params: {}, **_kwargs) ⇒ Object
59 60 61 |
# File 'lib/external_services/api.rb', line 59 def put(path, body:, params: {}, **_kwargs) request(:put, path, params, body) end |
#request(method, path, params = {}, body = nil) ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/external_services/api.rb', line 75 def request(method, path, params = {}, body = nil) resp = if fake? Struct.new(:success?, :body, :headers).new(true, fake_response_body(method, path, params), {}) else connection.send(method, path, body) do |req| req.params = params end end raise Error, resp unless resp.blank? || resp.success? resp end |