Sha256: 877a4a9b9df2b858a79ea0667623a67919c833348f7bd159747fe59a0a8dced5

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

require "net/https"
require "uri"
require "json"

class UnofficialBuildkiteClient
  class JsonApiClient
    def initialize(authorization_header: nil, logger:)
      @authorization_header = authorization_header
      @logger = logger
    end

    def request(method, url, params: nil)
      uri = URI.parse(url)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true

      logger.info("method: #{method}, url: #{url}, params: #{params.inspect}")

      request =
      case method
      when :get
        uri.query = URI.encode_www_form(params) if params
        Net::HTTP::Get.new(uri.request_uri)
      when :post
        Net::HTTP::Post.new(uri.request_uri).tap do |req|
          req.body = params.to_json if params
        end
      else
        raise NotImplementedError
      end

      json_headers.each do |k, v|
        request[k] = v
      end
      response = http.request(request)
      raise Error.new("#{response.inspect}") unless response.code.start_with?("2")
      JSON.parse(response.body, symbolize_names: true)
    end

    private

    attr_reader :logger

    def json_headers
      h = {
        "Content-Type" => "application/json",
        "Accept" => "application/json",
      }
      h.merge!("Authorization" => @authorization_header)
      h
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
unofficial_buildkite_client-0.3.0 lib/unofficial_buildkite_client/json_api_client.rb
unofficial_buildkite_client-0.2.0 lib/unofficial_buildkite_client/json_api_client.rb