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
17 18 19 |
# File 'lib/external_services/api.rb', line 17 def api_key ENV["#{to_s.demodulize.upcase}_API_KEY"] end |
#api_url ⇒ Object
13 14 15 |
# File 'lib/external_services/api.rb', line 13 def api_url ENV["#{to_s.demodulize.upcase}_API_URL"] end |
#auth_header ⇒ Object
21 22 23 |
# File 'lib/external_services/api.rb', line 21 def auth_header 'Authorization' end |
#connection ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/external_services/api.rb', line 25 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
52 53 54 |
# File 'lib/external_services/api.rb', line 52 def delete(path, params: {}, **_kwargs) request(:delete, path, params) end |
#fake? ⇒ Boolean
56 57 58 |
# File 'lib/external_services/api.rb', line 56 def fake? !connection end |
#fake_response_body(method, path, params = {}) ⇒ Object
60 61 62 |
# File 'lib/external_services/api.rb', line 60 def fake_response_body(method, path, params = {}) (method == :post ? { 'id' => SecureRandom.hex } : {}) end |
#get(path, params: {}, **_kwargs) ⇒ Object
40 41 42 |
# File 'lib/external_services/api.rb', line 40 def get(path, params: {}, **_kwargs) request(:get, path, params) end |
#post(path, body:, params: {}, **_kwargs) ⇒ Object
44 45 46 |
# File 'lib/external_services/api.rb', line 44 def post(path, body:, params: {}, **_kwargs) request(:post, path, params, body) end |
#put(path, body:, params: {}, **_kwargs) ⇒ Object
48 49 50 |
# File 'lib/external_services/api.rb', line 48 def put(path, body:, params: {}, **_kwargs) request(:put, path, params, body) end |
#request(method, path, params = {}, body = nil) ⇒ Object
64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/external_services/api.rb', line 64 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 |