Sha256: 37d42416d52902250a4c28359fc3ec36a60fbfecc6f10e1e66fd04e5b458b828
Contents?: true
Size: 1.87 KB
Versions: 1
Compression:
Stored size: 1.87 KB
Contents
# frozen_string_literal: true require 'faraday' require 'faraday_middleware' module ExternalServices module Api class Error < StandardError attr_reader :response def initialize(response) @response = response end def message @response.inspect end alias to_s message def inspect "#{self.class}: #{self}" end end def api_url ENV["#{to_s.demodulize.upcase}_API_URL"] end def api_key ENV["#{to_s.demodulize.upcase}_API_KEY"] end def auth_header 'Authorization' end 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 def get(path, params: {}, **_kwargs) request(:get, path, params) end def post(path, body:, params: {}, **_kwargs) request(:post, path, params, body) end def put(path, body:, params: {}, **_kwargs) request(:put, path, params, body) end def delete(path, params: {}, **_kwargs) request(:delete, path, params) end def fake? !connection end def fake_response_body(method, _path, _params = {}) (method == :post ? { 'id' => SecureRandom.hex } : {}) end 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 end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
external_services-0.5.4 | lib/external_services/api.rb |