Class: Seoshop::ResponseParser

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/seoshop-api/core/response_parser.rb

Defined Under Namespace

Classes: HTTPForbidden, HTTPNotFound, HTTPUnauthorized, RateLimit

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/seoshop-api/core/response_parser.rb', line 6

def call(env)
  # "env" contains the request
  @app.call(env).on_complete do
    body = false
    if env[:status] == 200
      body = env[:response].body.response || env[:response].body
    elsif env[:status] == 401
      raise HTTPUnauthorized.new 'invalid Seoshop credentials'
    elsif env[:status] == 403
      raise HTTPForbidden.new env[:response].body.message
    elsif env[:status] == 404
      raise HTTPNotFound.new env[:response].body.message
    elsif env[:status] == 429
      rate_limits = env[:response_headers]['X-RateLimit-Remaining'].split('/')
      rate_limits_reset = env[:response_headers]['X-RateLimit-Reset'].split('/')
      seconds = rate_limits_reset[0] if rate_limits[0] == '-1'
      seconds = rate_limits_reset[1] if rate_limits[1] == '-1'
      seconds = rate_limits_reset[2] if rate_limits[2] == '-1'
      raise RateLimit.new "RateLimit reset in #{seconds} seconds"
    elsif env[:response] && env[:response].body && env[:response].body.status
      body = env[:response].body.status
    end
    env[:body] = body
  end
end