Skip to content

Commit

Permalink
[#7] Update client service to match rebase code
Browse files Browse the repository at this point in the history
  • Loading branch information
malparty committed Jun 22, 2021
1 parent 6ab5dcc commit afebc04
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions app/services/google/client_service.rb
Expand Up @@ -5,36 +5,37 @@ class ClientService
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) '\
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'

BASE_SEARCH_URL2 = 'https://google.com/search'
BASE_SEARCH_URL = 'https://google.com/search'

def initialize(keyword:, lang: 'en')
escaped_keyword = CGI.escape(keyword)
@uri = URI("#{BASE_SEARCH_URL2}?q=#{escaped_keyword}&hl=#{lang}&gl=#{lang}")
@escaped_keyword = CGI.escape(keyword)
@uri = URI("#{BASE_SEARCH_URL}?q=#{@escaped_keyword}&hl=#{lang}&gl=#{lang}")
end

def call
begin
@result = HTTParty.get(@uri, { headers: { 'User-Agent' => USER_AGENT } })
rescue HTTParty::Error, Timeout::Error, SocketError => e
Rails.logger.error "Error: Query Google with keyword #{@keyword} throw an error: #{e}".colorize(:red)
@result = nil
else
validate_result
end
@result
result = HTTParty.get(@uri, { headers: { 'User-Agent' => USER_AGENT } })

return false unless valid_result? result

result
rescue HTTParty::Error, Timeout::Error, SocketError => e
Rails.logger.error "Error: Query Google with '#{@escaped_keyword}' thrown an error: #{e}".colorize(:red)

false
end

private

# Inspect Http response status code
# Any non 200 response code will be logged
# response is set to nil in order to notify the error
def validate_result
return if @result.response.code == '200'
def valid_result?(result)
return result if result&.response&.code == '200'

Rails.logger.warn "Warning: Query Google with '#{@escaped_keyword}' return status code #{result.response.code}"
.colorize(:yellow)

Rails.logger.warn "Warning: Query Google with keyword #{@keyword} return status code #{@result.response.code}"
.colorize(:yellow)
@result = nil
false
end
end
end

0 comments on commit afebc04

Please sign in to comment.