module ExternalServices::Api

Public Instance Methods

api_key() click to toggle source
# File lib/external_services/api.rb, line 28
def api_key
  ENV["#{to_s.demodulize.upcase}_API_KEY"]
end
api_url() click to toggle source
# File lib/external_services/api.rb, line 24
def api_url
  ENV["#{to_s.demodulize.upcase}_API_URL"]
end
auth_header() click to toggle source
# File lib/external_services/api.rb, line 32
def auth_header
  'Authorization'
end
connection() click to toggle source
# 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) click to toggle source
# File lib/external_services/api.rb, line 63
def delete(path, params: {}, **_kwargs)
  request(:delete, path, params)
end
fake?() click to toggle source
# File lib/external_services/api.rb, line 67
def fake?
  !connection
end
fake_response_body(method, _path, _params = {}) click to toggle source
# 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) click to toggle source
# File lib/external_services/api.rb, line 51
def get(path, params: {}, **_kwargs)
  request(:get, path, params)
end
post(path, body:, params: {}, **_kwargs) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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