BathHacked/energy-sparks

View on GitHub
lib/data_feeds/n3rgy/base_client.rb

Summary

Maintainability
A
0 mins
Test Coverage
module DataFeeds
  module N3rgy
    class BaseClient
      private

      def headers
        {
          'x-api-key': @api_key,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      end

      def http_connection(connection)
        connection || Faraday.new(@base_url, headers: headers)
      end

      # The n3rgy API returns errors in two ways. Either
      # a JSON response with a single message key, or an
      # array of errors, one per MPXN.
      def error_message(response)
        data = JSON.parse(response.body)
        if data['errors']
          error = data['errors'].first
          error['message']
        elsif data['message']
          data['message']
        else
          response.body
        end
      rescue
        # problem parsing or traversing json, return original api error
        response.body
      end
    end
  end
end