Sha256: 0889219f3324ac9c6b49a09bfe86d87f05ae1ca88d742b24ee40c5a38cf58f09

Contents?: true

Size: 763 Bytes

Versions: 2

Compression:

Stored size: 763 Bytes

Contents

require 'net/http'
require 'uri'
require 'json'
require 'timeout'
require_relative 'exceptions'

module ViaCep
  class Service
    BASE_URL = 'https://viacep.com.br/ws'.freeze

    # Fetches the ViaCEP API to request a CEP
    def self.fetch(cep, timeout)
      Timeout.timeout(timeout) do
        uri = URI("#{BASE_URL}/#{cep}/json")
        request = Net::HTTP.get_response(uri)

        if request.code == '200'
          response = JSON.parse(request.body)

          if response["erro"]
            raise ApiRequestError, "The server responded with HTTP 200 could not process the request"
          end

          response
        else
          raise ApiRequestError, "The server responded with HTTP #{request.code}"
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
viacep-2.0.2 lib/viacep/service.rb
viacep-2.0.1 lib/viacep/service.rb