Sha256: 0d7ef116e9b14a505c29868bd03f48dbf66a0e695e8120340f7f73d7ddce7572

Contents?: true

Size: 1.84 KB

Versions: 2

Compression:

Stored size: 1.84 KB

Contents

require 'net/http'
require 'json'

class Shoptet
  class Request
    def self.get url, headers
      http = Net::HTTP.new(url.host, url.port)
      http.use_ssl = true
      http.open_timeout = 30
      http.read_timeout = 30
      http.write_timeout = 30
      http.ssl_timeout = 30

      request = Net::HTTP::Get.new(url)
      headers.each do |key, value|
        request[key] = value
      end

      response = handle_net_timeouts { http.request(request) }
      parsed_body = JSON.parse(response.body)

      unless parsed_body
        message = "Status code: #{response.code}, url: #{url}"
        fail Shoptet::EmptyResponse.new(message)
      end

      parsed_body
    end

    def self.post url, body
      request = Net::HTTP::Post.new(url)
      request.set_form_data(body)

      response = Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
        handle_net_timeouts { http.request(request) }
      end

      JSON.parse(response.body)
    end

    def self.post_binary(url, body, headers)
      request = Net::HTTP::Post.new(url)
      request.body = body
      request.content_type = 'appliaction/octet-stream'
      headers.each do |key, value|
        request[key] = value
      end

      response = Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
        handle_net_timeouts { http.request(request) }
      end

      JSON.parse(response.body)
    end

    def self.delete(url, headers)
      request = Net::HTTP::Delete.new(url)
      headers.each do |key, value|
        request[key] = value
      end

      response = Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
        handle_net_timeouts { http.request(request) }
      end

      JSON.parse(response.body)
    end

    private

    def self.handle_net_timeouts
      begin
        yield
      rescue Net::OpenTimeout
        yield
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
shoptet-0.0.36 lib/shoptet/request.rb
shoptet-0.0.35 lib/shoptet/request.rb