requester.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. require "faraday"
  2. require "json"
  3. class Requester
  4. attr_reader :host, :conn
  5. def initialize(host, options={})
  6. @host = host
  7. @conn = init_conn
  8. end
  9. def json_send(http_method, path, params={}, headers={})
  10. res = @conn.send(http_method) do |req|
  11. req.url path
  12. req.headers['Content-Type'] = 'application/json'
  13. req.body = params.to_json
  14. end
  15. process_response(res)
  16. rescue => e
  17. error_response(e)
  18. end
  19. private
  20. def init_conn()
  21. Faraday.new(url: host, ssl: nil) do |faraday|
  22. faraday.request :url_encoded # form-encode POST params
  23. faraday.response :logger # log requests to $stdout
  24. faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
  25. end
  26. end
  27. def process_response(response)
  28. result = {'status' => response.status}
  29. begin
  30. body = Oj.load(response.body)
  31. body = body.is_a?(Hash) ? body : {'body' => body}
  32. body['body_status'] = body.delete('status') unless body['status'].is_a?(Integer)
  33. rescue
  34. body = {'body' => response.body}
  35. end
  36. result.merge(body)
  37. end
  38. def error_response(err)
  39. {'status' => 500, 'message' => "#{err.class.name}: #{err.message}"}
  40. end
  41. end