Skip to content

Commit

Permalink
[#6] Handle error while query google - not colorized
Browse files Browse the repository at this point in the history
  • Loading branch information
malparty committed Jun 16, 2021
1 parent 6a336f9 commit 91aacc3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 6 deletions.
4 changes: 3 additions & 1 deletion app/controllers/keywords_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ def index; end

def create
keyword = params['keyword']
raw_response = GoogleService::ClientService.query(keyword)
raw_response = GoogleService::ClientService.new(keyword).query_result

return redirect_to keywords_path, alert: I18n.t('keywords.could_not_query') unless raw_response

render :create, locals: {
keyword: keyword,
Expand Down
32 changes: 27 additions & 5 deletions app/services/google_service/client_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,34 @@ module GoogleService
class ClientService
require 'httparty'

def self.query(keyword, lang = 'en')
escaped_keyword = CGI.escape(keyword)
uri = URI("https://google.com/search?q=#{escaped_keyword}&hl=#{lang}&gl=#{lang}")
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) '\
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'
HTTParty.get(uri, { headers: { 'User-Agent' => user_agent } })

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

# 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'

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

def query_result
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}"
@result = nil
else
validate_result
end
@result
end
end
end
2 changes: 2 additions & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@
# available at https://guides.rubyonrails.org/i18n.html.

en:
keywords:
could_not_query: 'An error occurs when performing the Google Search, please try again.'
logout: "Sign out"

0 comments on commit 91aacc3

Please sign in to comment.