cpi-feed/cpi_fetcher.rb

52 lines
1.0 KiB
Ruby

# frozen_string_literal: true
require 'json'
require 'net/http'
require 'net/https'
require 'uri'
class CPIFetcher
DEFAULT_CPI_SERIES_URL = File.join(
'https://api.bls.gov',
'publicAPI/v2/timeseries/data/CUUSA210SA0'
)
private_constant :DEFAULT_CPI_SERIES_URL
attr_reader :url, :bls_token
def initialize
@url = URI(ENV['CPI_SERIES_URL'] || DEFAULT_CPI_SERIES_URL)
@bls_token = ENV.fetch('BLS_TOKEN')
end
def cpi
resp = fetch_raw_response
return nil unless resp['Results']['series']
data = resp['Results']['series'].first['data']
data.sort! { |a, b| a['year'] <=> b['year'] }
data.last['value']
end
private
def fetch_raw_response
http = Net::HTTP.new(url.hostname, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
res = http.request(build_request)
JSON.parse(res.body)
end
def build_request
req = Net::HTTP::Get.new(url)
req['Authorization'] = "token #{bls_token}"
req
end
end
if $PROGRAM_NAME == __FILE__
puts CPIFetcher.new.cpi
exit 0
end