module Xhash::JsonApi::ClassMethods

Public Instance Methods

api_get(url:, headers: {}) click to toggle source
# File lib/xhash/client/json_api.rb, line 12
def api_get(url:, headers: {})
  custom_headers = headers.merge(default_headers)
  response = HTTParty.get(Xhash.api_base + url, headers: custom_headers, timeout: Xhash.timeout)

  raise Xhash::Error.new(response) unless response_ok?(response)

  begin
    JSON.parse(response.body, symbolize_names: true)
  rescue => exception
    raise Xhash::MalformedResponse.new
  end
end
api_post(url:, body: {}, headers: {}) click to toggle source
# File lib/xhash/client/json_api.rb, line 25
def api_post(url:, body: {}, headers: {})
  custom_headers = headers.merge(default_headers)

  response =
    HTTParty.post(
      Xhash.api_base + url,
      body: body.to_json, headers: custom_headers, timeout: Xhash.timeout
    )

  raise Xhash::Error.new(response) unless response_ok?(response)

  begin
    JSON.parse(response.body, symbolize_names: true)
  rescue => exception
    raise Xhash::MalformedResponse.new
  end
end
api_post_multipart(url:, body: {}, headers: {}) click to toggle source
# File lib/xhash/client/json_api.rb, line 43
def api_post_multipart(url:, body: {}, headers: {})
  custom_headers = headers.merge(default_headers)

  response =
    HTTParty.post(
      Xhash.api_base + url,
      multipart: true, body: body, headers: custom_headers, timeout: Xhash.timeout
    )

  raise Xhash::Error.new(response) unless response_ok?(response)
  response.body
end
default_headers() click to toggle source
# File lib/xhash/client/json_api.rb, line 6
def default_headers
  {
    'Content-type' => 'application/json', 'Authorization' => Xhash.api_key
  }
end
response_ok?(response) click to toggle source
# File lib/xhash/client/json_api.rb, line 56
def response_ok?(response)
  !(response.code == 404 || response.code >= 500)
end