Class: GenericApi::Middleware

Inherits:
Faraday::Request::BasicAuthentication
  • Object
show all
Defined in:
lib/wfa/generic_api.rb

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/wfa/generic_api.rb', line 56

def call(env)
  # encode with and accept json
  env[:request_headers]['Accept'] = MIME_TYPE
  env[:request_headers]['Content-Type'] = MIME_TYPE
  env[:body] = Yajl::Encoder.encode(env[:body]) if env[:body]

  # response processing
  super(env).on_complete do |env|
    begin
      env[:body] = Yajl::Parser.parse(env[:body], symbolize_keys:true)
      # XXX or, if you're using ActiveSupport:
      # env[:body] = Yajl::Parser.parse(env[:body]).with_indifferent_access
    rescue Yajl::ParseError
      raise ApiError.new("Unable to parse the response:\n#{env[:body]}", env)
    end
    case env[:status]
    when 300..399
      raise RedirectError.new(env[:body][:message], env)
    when 400..499
      raise AuthError.new(env[:body][:message], env)
    when 500..599
      raise ApiError.new(env[:body][:message], env)
    end
  end
end