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 28, 2021
1 parent cc12927 commit 518f3d5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
11 changes: 9 additions & 2 deletions app/controllers/keywords_controller.rb
Expand Up @@ -4,7 +4,14 @@ class KeywordsController < ApplicationController
def index; end

def create
@keyword = params['keyword']
@raw_response = GoogleService::ClientService.query(@keyword)
keyword = params['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,
raw_response: raw_response
}
end
end
37 changes: 37 additions & 0 deletions app/services/google_service/client_service.rb
@@ -0,0 +1,37 @@
# frozen_string_literal: true

module GoogleService
class ClientService
require 'httparty'

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'

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

0 comments on commit 518f3d5

Please sign in to comment.