module PlentyClient::Request::ClassMethods

Public Instance Methods

delete(path, body = {}) click to toggle source
# File lib/plenty_client/request.rb, line 32
def delete(path, body = {})
  request(:delete, path, body)
end
get(path, params = {}) { |response| ... } click to toggle source
# File lib/plenty_client/request.rb, line 36
def get(path, params = {})
  page = 1
  rval_array = []
  if block_given?
    loop do
      response = request(:get, path, params.merge('page' => page))
      yield response['entries']
      break if response['isLastPage'] == true
      page += 1
    end
  else
    rval_array = request(:get, path, { 'page' => page }.merge(params))
  end
  return rval_array.flatten if rval_array.is_a?(Array)
  rval_array
end
patch(path, body = {}) click to toggle source
# File lib/plenty_client/request.rb, line 28
def patch(path, body = {})
  request(:patch, path, body)
end
post(path, body = {}) click to toggle source
# File lib/plenty_client/request.rb, line 20
def post(path, body = {})
  request(:post, path, body)
end
put(path, body = {}) click to toggle source
# File lib/plenty_client/request.rb, line 24
def put(path, body = {})
  request(:put, path, body)
end
request(http_method, path, params = {}) click to toggle source
# File lib/plenty_client/request.rb, line 7
def request(http_method, path, params = {})
  raise ArgumentError, "http_method or path is missing" if http_method.nil? || path.nil?
  unless %w[post put patch delete get].include?(http_method.to_s)
    raise ArgumentError, "unsupported http_method: #{http_method}"
  end

  login_check unless PlentyClient::Config.tokens_valid?

  params = stringify_symbol_keys(params) if params.is_a?(Hash)

  perform(http_method, path, params)
end

Private Instance Methods

assert_success_status_code(response) click to toggle source
# File lib/plenty_client/request.rb, line 159
def assert_success_status_code(response)
  case response.status
  when 300..399
    raise RedirectionError, "Invalid response: HTTP status: #{response.status}: #{response.body}"
  when 400..499
    raise ClientError, "Invalid response: HTTP status: #{response.status}: #{response.body}"
  when 500..599
    raise ServerError, "Invalid response: HTTP status: #{response.status}: #{response.body}"
  end
end
base_url(path) click to toggle source
# File lib/plenty_client/request.rb, line 100
def base_url(path)
  uri = URI(PlentyClient::Config.site_url)
  url = "#{uri.scheme}://#{uri.host}/rest"
  url += path.start_with?('/') ? path : "/#{path}"
  url
end
check_for_invalid_credentials(response) click to toggle source
# File lib/plenty_client/request.rb, line 144
def check_for_invalid_credentials(response)
  raise PlentyClient::Config::InvalidCredentials if response['error'] == 'invalid_credentials'
end
error_check(response) click to toggle source
# File lib/plenty_client/request.rb, line 136
def error_check(response)
  return if response.nil? || response&.empty?
  response = response.first if response.is_a?(Array)
  return unless response&.key?('error')
  check_for_invalid_credentials(response)
  extract_message(response)
end
extract_message(response) click to toggle source
# File lib/plenty_client/request.rb, line 148
def extract_message(response)
  if response.key?('validation_errors') && response['validation_errors'] && !response['validation_errors']&.empty?
    errors = response['validation_errors']
    rval = errors.values         if response['validation_errors'].is_a?(Hash)
    rval = errors.flatten.values if response['validation_errors'].is_a?(Array)
    rval.flatten.join(', ')
  else
    response.dig('error', 'message')
  end
end
headers(adapter) click to toggle source
# File lib/plenty_client/request.rb, line 91
def headers(adapter)
  adapter.headers['Content-type'] = 'application/json'
  unless PlentyClient::Config.access_token.nil?
    adapter.headers['Authorization'] = "Bearer #{PlentyClient::Config.access_token}"
  end
  adapter.headers['Accept'] = 'application/x.plentymarkets.v1+json'
  adapter
end
login_check() click to toggle source
# File lib/plenty_client/request.rb, line 64
def login_check
  PlentyClient::Config.validate_credentials
  result = perform(:post, '/login', username: PlentyClient::Config.api_user,
                                    password: PlentyClient::Config.api_password)
  PlentyClient::Config.access_token  = result['accessToken']
  PlentyClient::Config.refresh_token = result['refreshToken']
  PlentyClient::Config.expiry_date   = Time.now + result['expiresIn']
end
parse_body(response) click to toggle source
# File lib/plenty_client/request.rb, line 117
def parse_body(response)
  return nil if response.body.strip == ""
  content_type = response.env.response_headers['Content-Type']
  case content_type
  when %r{(?:application|text)/json}
    json = JSON.parse(response.body)
    errors = error_check(json)
    raise PlentyClient::NotFound, errors if errors.is_a?(String) && errors =~ /no query results/i
    raise PlentyClient::ResponseError, errors if errors && !errors&.empty?
    json
  when %r{application/pdf}
    response.body
  else
    raise PlentyClient::ResponseError, "unsupported response Content-Type: #{content_type}"
  end
rescue JSON::ParserError
  raise PlentyClient::ResponseError, 'invalid response'
end
perform(http_method, path, params = {}) click to toggle source
# File lib/plenty_client/request.rb, line 73
def perform(http_method, path, params = {})
  conn = Faraday.new(url: PlentyClient::Config.site_url) do |faraday|
    faraday = headers(faraday)
    if PlentyClient::Config.log
      faraday.response :logger do |logger|
        logger.filter(/password=([^&]+)/, 'password=[FILTERED]')
      end
    end
  faraday.request :retry, max: PlentyClient::Config.attempt_count
  end
  conn.adapter :typhoeus
  verb = http_method.to_s.downcase
  params = params.to_json unless %w[get delete].include?(verb)
  response = conn.send(verb, base_url(path), params)
  assert_success_status_code(response)
  parse_body(response)
end
stringify_symbol_keys(hash) click to toggle source
# File lib/plenty_client/request.rb, line 55
def stringify_symbol_keys(hash)
  new_hash = {}
  hash.each do |k, v|
    k = k.to_s if k.is_a?(Symbol)
    new_hash[k] = v
  end
  new_hash
end
throttle_check_short_period(response_header) click to toggle source

2017-12-04 DO: there has to be a supervisor watching over the users limits

BEFORE the request actually happens
response_header is after the request and useless if you have multiple instances of the Client
# File lib/plenty_client/request.rb, line 110
def throttle_check_short_period(response_header)
  short_calls_left = response_header['X-Plenty-Global-Short-Period-Calls-Left']
  short_seconds_left = response_header['X-Plenty-Global-Short-Period-Decay']
  return if short_calls_left&.empty? || short_seconds_left&.empty?
  sleep(short_seconds_left.to_i + 1) if short_calls_left.to_i <= 10 && short_seconds_left.to_i < 3
end