Skip to content
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* [Unreleased] Raise `SerpApiError` instead of `TypeError` for non-200 responses whose `error` or `search_metadata.id` is not a String
* [Unreleased] Report the HTTP status instead of a JSON parse error for non-200 responses whose body is not JSON, such as a Cloudflare error page
* [Unreleased] Raise `SerpApiError` instead of an `EncodingError` for responses whose body doesn't match the charset in their Content-Type
* [Unreleased] Stop `Client.new` from modifying the params hash passed in, and accept frozen hashes
* [Unreleased] Read `api_key`, `engine`, `timeout`, `persistent`, and `symbolize_names` given with String keys, and stop sending a String `symbolize_names` key to the API
* [Unreleased] Add native Extract API support via the `extract` method
* [Unreleased] Apply the `timeout` option to persistent connections
* [Unreleased] Add Image API support
Expand Down
28 changes: 14 additions & 14 deletions lib/serpapi/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,16 @@ def initialize(params = {})
raise SerpApiError, "params must be hash, not: #{params.class}" unless params.instance_of?(Hash)

# store client HTTP request timeout
@timeout = params[:timeout] || 120
@timeout = option(params, :timeout) || 120
@timeout.freeze

# enable HTTP persistent mode
@persistent = true
@persistent = params[:persistent] if params.key?(:persistent)
@persistent = option(params, :persistent, true)
@persistent.freeze

# delete this client only configuration keys
%i[timeout persistent].each do |option|
params.delete(option) if params.key?(option)
end

# set default query parameters
@params = params.clone || {}
# set default query parameters without the client only configuration keys
# (reject returns a new hash, so the caller's hash is never modified)
@params = params.reject { |key, _| [:timeout, :persistent].any? { |name| name.to_s == key.to_s } }

# ensure default parameter would not be modified later
@params.freeze
Expand Down Expand Up @@ -264,12 +259,12 @@ def account(api_key = nil)

# @return [String] default search engine
def engine
@params[:engine]
option(@params, :engine)
end

# @return [String] api_key user secret API key as provided to the constructor
def api_key
@params[:api_key]
option(@params, :api_key)
end

# close open connection if active
Expand All @@ -291,6 +286,11 @@ def inspect

private

# Read an option passed with either a Symbol or a String key, the Symbol key first.
def option(hash, name, default = nil)
hash.fetch(name) { hash.fetch(name.to_s, default) }
end

def force_output(params, format)
return params unless params.is_a?(Hash)

Expand All @@ -308,7 +308,7 @@ def query(params)
q.delete(:output) if params.key?('output') && !params.key?(:output)

# do not pollute default params with custom params
q.delete(:symbolize_names) if q.key?(:symbolize_names)
q.delete_if { |key, _| key.to_s == 'symbolize_names' }

# delete empty key/value
q.compact
Expand Down Expand Up @@ -396,7 +396,7 @@ def error_details(response)
end

def parse_json(response, endpoint, params)
JSON.parse(response.body, symbolize_names: params.fetch(:symbolize_names, true))
JSON.parse(response.body, symbolize_names: option(params, :symbolize_names, true))
rescue JSON::ParserError, EncodingError
raise_parser_error(response, endpoint, params)
end
Expand Down
64 changes: 64 additions & 0 deletions spec/serpapi/client/constructor_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
require 'spec_helper'

# These specs only build clients, so they make no HTTP request to serpapi.com.
describe 'SerpApi::Client constructor' do
it 'does not modify the params hash passed by the caller' do
config = { engine: 'google', api_key: 'test_key', timeout: 10, persistent: false }
original = config.dup

SerpApi::Client.new(config)

expect(config).to eq(original)
end

it 'gives the same settings to every client built from a reused config hash' do
config = { engine: 'google', api_key: 'test_key', timeout: 10, persistent: false }

first = SerpApi::Client.new(config)
second = SerpApi::Client.new(config)

expect(second.timeout).to eq(first.timeout)
expect(second.timeout).to eq(10)
expect(second.persistent).to be false
expect(second.socket).to be_nil
end

it 'accepts a frozen params hash' do
config = { engine: 'google', api_key: 'test_key', timeout: 10, persistent: false }.freeze

client = SerpApi::Client.new(config)

expect(client.timeout).to eq(10)
expect(client.persistent).to be false
expect(client.engine).to eq('google')
end

it 'keeps timeout and persistent out of the query parameters' do
client = SerpApi::Client.new(engine: 'google', api_key: 'test_key', timeout: 10, persistent: false)

expect(client.params).not_to have_key(:timeout)
expect(client.params).not_to have_key(:persistent)
end

it 'reads client options and defaults passed with String keys' do
config = { 'engine' => 'google', 'api_key' => 'test_key', 'timeout' => 10, 'persistent' => false }

client = SerpApi::Client.new(config)

expect(client.engine).to eq('google')
expect(client.api_key).to eq('test_key')
expect(client.timeout).to eq(10)
expect(client.persistent).to be false
expect(client.socket).to be_nil
expect(client.params).to eq('engine' => 'google', 'api_key' => 'test_key')
end

it 'defaults to a 120 second timeout and persistent mode' do
client = SerpApi::Client.new(engine: 'google', api_key: 'test_key')

expect(client.timeout).to eq(120)
expect(client.persistent).to be true
expect(client.socket).not_to be_nil
client.close
end
end
30 changes: 30 additions & 0 deletions spec/serpapi/client/symbolize_names_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
require 'spec_helper'

# These specs stub the HTTP client, so they make no HTTP request to serpapi.com.
describe 'symbolize_names search option' do
let(:http) { double }
let(:client) { SerpApi::Client.new(api_key: 'test-key', engine: 'google', persistent: false) }
let(:response) do
double(status: 200, body: '{"search_metadata":{"id":"1"}}', headers: { 'Content-Type' => 'application/json' })
end

before do
allow(HTTP).to receive(:timeout).and_return(double(headers: http))
allow(http).to receive(:get).and_return(response)
end

[:symbolize_names, 'symbolize_names'].each do |key|
it "returns String keys and keeps #{key.inspect} out of the request" do
results = client.search(q: 'coffee', key => false)

expect(results).to eq('search_metadata' => { 'id' => '1' })
expect(http).to have_received(:get) do |_url, options|
expect(options[:params].keys.map(&:to_s)).not_to include('symbolize_names')
end
end
end

it 'returns Symbol keys by default' do
expect(client.search(q: 'coffee')).to eq(search_metadata: { id: '1' })
end
end
Loading