Sha256: 77a93392743d0d8e199600cb1e9b390606dfd4ae39f4fd771cd0cffe557f1843

Contents?: true

Size: 942 Bytes

Versions: 3

Compression:

Stored size: 942 Bytes

Contents

require 'uri'
require 'net/http'
require 'json'

module Arbetsformedlingen
  module API
    class Request
      Response = KeyStruct.new(:code, :body, :json)

      attr_reader :locale, :base_url

      def initialize(base_url: '', locale: 'sv')
        @base_url = base_url
        @locale = locale
      end

      def get(url, query: {})
        uri = URI("#{base_url}#{url}?#{URI.encode_www_form(query.to_a)}")

        http = Net::HTTP.new(uri.host, uri.port)

        request = Net::HTTP::Get.new(uri)
        request['Content-Type'] = 'application/json'
        request['Accept-Language'] = locale

        response = http.request(request)

        Response.new(
          code: response.code,
          body: response.read_body,
          json: parse_json(response.read_body)
        )
      end

      def parse_json(string)
        JSON.parse(string.to_s)
      rescue JSON::ParserError => _e
        {}
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
arbetsformedlingen-0.5.0 lib/arbetsformedlingen/api/request.rb
arbetsformedlingen-0.4.1 lib/arbetsformedlingen/api/request.rb
arbetsformedlingen-0.4.0 lib/arbetsformedlingen/api/request.rb