Class: PolyLingo::HttpClient
- Inherits:
-
Object
- Object
- PolyLingo::HttpClient
- Defined in:
- lib/polylingo/http_client.rb
Overview
net/http wrapper: auth, JSON, timeouts (seconds), error mapping.
Constant Summary collapse
- DEFAULT_BASE_URL =
"https://api.usepolylingo.com/v1"
Instance Method Summary collapse
-
#initialize(api_key:, base_url:, timeout:) ⇒ HttpClient
constructor
A new instance of HttpClient.
-
#request(path, method:, body: nil, expect_status: 200) ⇒ Object
expect_statusmay be a single Integer or an Array of acceptable statuses.
Constructor Details
#initialize(api_key:, base_url:, timeout:) ⇒ HttpClient
Returns a new instance of HttpClient.
12 13 14 15 16 |
# File 'lib/polylingo/http_client.rb', line 12 def initialize(api_key:, base_url:, timeout:) @api_key = api_key @base_url = base_url.chomp("/") @timeout = timeout end |
Instance Method Details
#request(path, method:, body: nil, expect_status: 200) ⇒ Object
expect_status may be a single Integer or an Array of acceptable statuses.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/polylingo/http_client.rb', line 19 def request(path, method:, body: nil, expect_status: 200) path = path.start_with?("/") ? path : "/#{path}" uri = URI("#{@base_url}#{path}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == "https" http.open_timeout = @timeout http.read_timeout = @timeout req = build_request(uri, method, body) begin res = http.request(req) rescue Net::OpenTimeout, Net::ReadTimeout, Errno::ETIMEDOUT raise PolyLingoError.new(408, "timeout", "Request timed out after #{@timeout}s") end text = res.body.to_s parsed = parse_body(text) expected = Array(expect_status).map(&:to_i) unless expected.include?(res.code.to_i) raise error_from_response(res.code.to_i, parsed, res) end parsed end |