Skip to content

Instantly share code, notes, and snippets.

@abhinaykumar
Created June 26, 2022 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhinaykumar/10ea2f5d86a049a3b791f82c468623d7 to your computer and use it in GitHub Desktop.
Save abhinaykumar/10ea2f5d86a049a3b791f82c468623d7 to your computer and use it in GitHub Desktop.
Common class to make HTTP requests using Faraday. Parallel POST requests with Faraday and Typhoeus Hydra.
class Http
class << self
def send_request(url, options = {}, verb = :get)
headers = options[:headers]
headers = headers.present? ? default_headers.merge(headers) : default_headers
body = options[:body].presence
body = body.to_json if headers['Content-Type'] == 'application/json'
query = options[:query].presence
payload = verb == :get ? query : body
response = Faraday.public_send(verb, url, payload, headers)
parsed_response(response.body)
rescue StandardError => e
raise 'Invalid request'
end
# Only for :post request for now
def send_parallel_request(url, options = {}, verb = :post)
custom_headers = options[:headers]
headers = custom_headers.present? ? default_headers.merge(custom_headers) : default_headers
manager = Typhoeus::Hydra.new(max_concurrency: 10)
connection = Faraday.new(url: url, parallel_manager: manager) do |faraday|
faraday.adapter :typhoeus
end
responses = []
connection.in_parallel do
options[:body].each do |payload|
responses << Faraday.public_send(verb, url, payload.to_json, headers)
end
end
parsed_response(successful_requests)
end
def default_headers
{
'Content-Type' => 'application/json',
'Accept' => '*/*'
}
end
def parsed_response(response)
response = response.map { |res| JSON.parse(res.body).deep_symbolize_keys! } if response.is_a?(Array)
response = JSON.parse(response).deep_symbolize_keys! if response.is_a?(String)
response
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment