Class: Pickpoint::Transport::Client
- Inherits:
-
Object
- Object
- Pickpoint::Transport::Client
- Defined in:
- lib/pickpoint/transport.rb
Instance Method Summary collapse
- #do(opts) ⇒ Object
-
#initialize(base_url:, http:, auth:, max_retries:, retry_base:) ⇒ Client
constructor
A new instance of Client.
Constructor Details
#initialize(base_url:, http:, auth:, max_retries:, retry_base:) ⇒ Client
Returns a new instance of Client.
28 29 30 31 32 33 34 |
# File 'lib/pickpoint/transport.rb', line 28 def initialize(base_url:, http:, auth:, max_retries:, retry_base:) @base_url = base_url @http = http @auth = auth @max_retries = max_retries @retry_base = retry_base end |
Instance Method Details
#do(opts) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/pickpoint/transport.rb', line 36 def do(opts) attempt = 0 auth_retried = false loop do url = build_url(opts) headers = {} @auth.apply!(headers) body = opts.body.nil? ? nil : JSON.generate(opts.body) headers["Content-Type"] = "application/json" unless body.nil? begin status, raw = @http.request(opts.method || "GET", url, headers: headers, body: body) rescue StandardError => e raise APIError.new(code: "NETWORK", message: "network error: #{e}") if attempt >= @max_retries sleep_backoff(attempt) attempt += 1 next end if status == 401 if !auth_retried && @auth.bearer? && @auth. auth_retried = true next end raise APIError.new(status: status, code: "API_AUTH", message: "auth failed (401)", body: raw) end if [402, 403].include?(status) raise APIError.new(status: status, code: "API_AUTH", message: "auth failed", body: raw) end return "" if status == 204 if status == 409 raise APIError.new( status: 409, code: "CONFLICT", message: (raw, 409), body: raw ) end if status == 400 || (status >= 404 && status < 500) return opts.empty || "" if opts.on_client_error == ON_EMPTY code = status == 404 ? "NOT_FOUND" : "CLIENT_ERROR" raise APIError.new( status: status, code: code, message: (raw, status), body: raw ) end if status >= 500 if attempt >= @max_retries raise APIError.new( status: status, code: "SERVER_ERROR", message: "server error after retries", body: raw ) end sleep_backoff(attempt) attempt += 1 next end return raw if status >= 200 && status < 300 return opts.empty || "" if status >= 400 && status < 500 && opts.on_client_error == ON_EMPTY raise APIError.new( status: status, code: "CLIENT_ERROR", message: (raw, status), body: raw ) end end |