Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class HTTPClient
- class Error < StandardError; end
- class Response
- attr_reader :status, :body, :headers, :message
- def initialize(status, body, headers, success = nil, message = nil)
- @status = status
- @body = body
- @headers = headers
- @success = !!success # converts to bool if necessary
- @message = message
- end
- def success?
- @success
- end
- end
- # STATUS = {
- # 400 => 'Bad Request',
- # 401 => 'Unauthorized',
- # 403 => 'Forbidden',
- # 404 => 'Resource not found',
- # 500 => 'Internal Server Error',
- # 502 => 'Bad Gateway',
- # 503 => 'Service Unavailable',
- # 504 => 'Gateway Time-out'
- # }
- def initialize(global_headers: {}, user: nil, password: nil)
- @http_client = Faraday.new do |conn|
- conn.use FaradayMiddleware::FollowRedirects # needed for resource manager
- conn.use Faraday::CustomErrors
- conn.request :multipart
- conn.request :url_encoded
- conn.adapter :net_http
- end
- # global headers used in every request.
- @http_client.headers.merge!(global_headers)
- # NOTE: basic auth can't be set in a per request basis
- @http_client.basic_auth user, password if (user.present? and password.present?)
- end
- def get(attrs = {})
- run_request(attrs.merge method: :get)
- end
- def post(attrs = {})
- run_request(attrs.merge method: :post)
- end
- def put(attrs = {})
- run_request(attrs.merge method: :put)
- end
- def delete(attrs = {})
- run_request(attrs.merge method: :delete)
- end
- def run_request(method:, url:, body: nil, params: {}, headers: {})
- begin
- Rails.logger.info({
- message: "[HTTP] #{method.to_s} request",
- url: url,
- params: params,
- headers: headers,
- body: body,
- method: method.to_s,
- })
- response = @http_client.send(method) do |request|
- request.url url
- request.body body if body.present?
- request.headers.merge!(headers)
- request.params.merge!(params)
- end
- HTTPClient::Response.new(response.status, response.body, response.headers, response.success?)
- rescue Faraday::Error => error
- Support::LogHelpers.error(error)
- raise HTTPClient::Error, error.message
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement