Skip to content

Client: Improve query params with specs #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions lib/tenkit/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,21 @@ def initialize
Tenkit.config.validate!
end

def availability(lat, lon, country: 'US')
get("/availability/#{lat}/#{lon}?country=#{country}")
def availability(lat, lon, **options)
options[:country] ||= 'US'

query = { country: options[:country] }
get("/availability/#{lat}/#{lon}", query: query)
end

def weather(lat, lon, data_sets: [:current_weather], language: 'en')
path_root = "/weather/#{language}/#{lat}/#{lon}?dataSets="
path = path_root + data_sets.map { |ds| DATA_SETS[ds] }.compact.join(',')
response = get(path)
def weather(lat, lon, **options)
options[:data_sets] ||= [:current_weather]
options[:language] ||= 'en'

query = weather_query_for_options(options)
path = "/weather/#{options[:language]}/#{lat}/#{lon}"

response = get(path, query: query)
WeatherResponse.new(response)
end

Expand All @@ -43,9 +50,11 @@ def weather_alert(id, language: 'en')

private

def get(url)
def get(url, query: nil)
headers = { Authorization: "Bearer #{token}" }
self.class.get(url, { headers: headers })
params = { headers: headers }
params[:query] = query unless query.nil?
self.class.get(url, params)
end

def header
Expand All @@ -72,5 +81,22 @@ def key
def token
JWT.encode payload, key, 'ES256', header
end

# Snake case options to expected query parameters
# https://developer.apple.com/documentation/weatherkitrestapi/get-api-v1-weather-_language_-_latitude_-_longitude_#query-parameters
def weather_query_for_options(options)
data_sets_param = options[:data_sets].map { |ds| DATA_SETS[ds] }.compact.join(',')

{
countryCode: options[:country_code],
currentAsOf: options[:current_as_of],
dailyEnd: options[:daily_end],
dailyStart: options[:daily_start],
dataSets: data_sets_param,
hourlyEnd: options[:hourly_end],
hourlyStart: options[:hourly_start],
timezone: options[:timezone]
}.compact
end
end
end
6 changes: 6 additions & 0 deletions lib/tenkit/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,11 @@ def self.snake(str)

str.gsub(/(.)([A-Z])/, '\1_\2').sub(/_UR_L$/, "_URL").downcase
end

def self.camel(str)
return str.camelize(:lower) if str.respond_to? :camelize

str.gsub(/_(.)/) {|e| $1.upcase}
end
end
end
25 changes: 22 additions & 3 deletions spec/tenkit/tenkit/utils_spec.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
require_relative "../spec_helper"
RSpec.describe Tenkit::Utils do
let(:camel) { "someSpecialCaseString" }
let(:snake) { "some_special_case_string" }

subject { Tenkit::Utils }

describe ".snake" do
let(:simple) { "someCamelCaseString" }
let(:correct) { "some_camel_case_string" }
let(:complex) { "someAWSCredentials" }
let(:mangled) { "some_aw_scredentials" }

it "converts to snake case" do
expect(subject.snake(simple)).to eq correct
expect(subject.snake(camel)).to eq snake
end

context "when passed an acronym" do
Expand All @@ -26,10 +27,28 @@
end
end
end

describe ".camel" do
it "converts to camel case" do
expect(subject.camel(snake)).to eq camel
end

context "when a proper camelize package is available" do
let(:patched_string) { PatchedString.new snake }

it "uses string camelize method" do
expect(subject.camel(patched_string)).to eq :correct
end
end
end
end

class PatchedString < String
def underscore
:correct
end

def camelize(sym)
:correct
end
end
73 changes: 49 additions & 24 deletions spec/tenkit/tenkit/weather_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,69 @@
RSpec.describe Tenkit::Weather do
let(:lat) { 37.32 }
let(:lon) { 122.03 }
let(:path) { "/weather/en/#{lat}/#{lon}" }
let(:params) { {dataSets: data_set} }
let(:client) { Tenkit::Client.new }
let(:api_response) { double("WeatherResponse", body: json) }
let(:json) { File.read("test/fixtures/#{data_set}.json") }
let(:resp) { double("WeatherResponse", body: json) }
let(:data_sets) { [Tenkit::Utils.snake(data_set).to_sym] }

before { allow(client).to receive(:get).and_return(api_response) }
before { expect(client).to receive(:get).with(path, {query: params}).and_return(resp) }

describe "currentWeather" do
let(:data_set) { "currentWeather" }

subject { client.weather(lat, lon).weather.current_weather }

it "includes expected metadata" do
expect(subject.name).to eq "CurrentWeather"
expect(subject.metadata.attribution_url).to start_with 'https://'
expect(subject.metadata.latitude).to be 37.32
expect(subject.metadata.longitude).to be 122.03
context "with options" do
let(:fmt) { "%FT%TZ" }
let(:now) { Time.now }
let(:options) do
{country_code: "US",
current_as_of: now.strftime(fmt),
daily_end: (now + 12 * 3600).strftime(fmt),
daily_start: (now - 12 * 3600).strftime(fmt),
data_sets: data_sets,
hourly_end: (now + 6 * 3600).strftime(fmt),
hourly_start: (now - 6 * 3600).strftime(fmt),
timezone: "PST"}
end
let(:params) do
options.map { |k, v| [Tenkit::Utils.camel(k.to_s).to_sym, (k == :data_sets) ? data_set : v] }.to_h
end

subject { client.weather(lat, lon, **options).weather.current_weather }

it "includes expected metadata" do
expect(subject.name).to eq "CurrentWeather"
expect(subject.metadata.attribution_url).to start_with "https://"
expect(subject.metadata.latitude).to be 37.32
expect(subject.metadata.longitude).to be 122.03
end

it "returns correct object types" do
expect(subject).to be_a Tenkit::CurrentWeather
expect(subject.metadata).to be_a Tenkit::Metadata
end

it "returns current weather data" do
expect(subject.temperature).to be(-5.68)
expect(subject.temperature_apparent).to be(-6.88)
end
end

it "returns correct object types" do
expect(subject).to be_a Tenkit::CurrentWeather
expect(subject.metadata).to be_a Tenkit::Metadata
end
context "without options" do
subject { client.weather(lat, lon).weather.current_weather }

it "returns current weather data" do
expect(subject.temperature).to be(-5.68)
expect(subject.temperature_apparent).to be(-6.88)
it "returns response" do
expect(subject.name).to eq "CurrentWeather"
end
end
end

describe "forecastDaily" do
let(:data_set) { "forecastDaily" }
let(:first_day) { subject.days.first }

subject { client.weather(lat, lon).weather.forecast_daily }
subject { client.weather(lat, lon, data_sets: data_sets).weather.forecast_daily }

it "returns 10 days of data" do
expect(subject.days.size).to be 10
Expand All @@ -50,13 +79,9 @@
expect(first_day.rest_of_day_forecast).to be_a Tenkit::RestOfDayForecast
end

it "excludes learn_more_url node" do
expect(subject.respond_to? :learn_more_url).to be false
end

it "includes expected metadata" do
expect(subject.name).to eq "DailyForecast"
expect(subject.metadata.attribution_url).to start_with 'https://'
expect(subject.metadata.attribution_url).to start_with "https://"
expect(subject.metadata.latitude).to be 37.32
expect(subject.metadata.longitude).to be 122.03
end
Expand All @@ -80,15 +105,15 @@
let(:data_set) { "forecastHourly" }
let(:first_hour) { subject.hours.first }

subject { client.weather(lat, lon).weather.forecast_hourly }
subject { client.weather(lat, lon, data_sets: data_sets).weather.forecast_hourly }

it "returns 25 hours of data" do
expect(subject.hours.size).to be 25
end

it "includes expected metadata" do
expect(subject.name).to eq "HourlyForecast"
expect(subject.metadata.attribution_url).to start_with 'https://'
expect(subject.metadata.attribution_url).to start_with "https://"
expect(subject.metadata.latitude).to be 37.32
expect(subject.metadata.longitude).to be 122.03
end
Expand Down