Class: SparkApi::FaradayMiddleware

Inherits:
Faraday::Response::Middleware
  • Object
show all
Includes:
PaginateHelper
Defined in:
lib/spark_api/faraday_middleware.rb

Overview

Spark API Faraday middleware

HTTP Response after filter to package api responses and bubble up basic api errors.

Instance Method Summary collapse

Methods included from PaginateHelper

#paginate_response

Constructor Details

#initialize(app) ⇒ FaradayMiddleware

Returns a new instance of FaradayMiddleware.



11
12
13
# File 'lib/spark_api/faraday_middleware.rb', line 11

def initialize(app)
  super(app)
end

Instance Method Details

#decompress_body(env) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/spark_api/faraday_middleware.rb', line 70

def decompress_body(env)
  encoding = env[:response_headers]['content-encoding'].to_s.downcase

  if encoding == 'gzip'
    env[:body] = Zlib::GzipReader.new(StringIO.new(env[:body])).read
  elsif encoding == 'deflate'
    env[:body] = Zlib::Inflate.inflate(env[:body])
  end

  env[:body]
end

#on_complete(env) ⇒ Object

Handles pretty much all the api response parsing and error handling. All responses that indicate a failure will raise a SparkApi::ClientError exception



17
18
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/spark_api/faraday_middleware.rb', line 17

def on_complete(env)

  env[:body] = decompress_body(env)

  body = MultiJson.decode(env[:body])
  SparkApi.logger.debug("Response Body: #{body.inspect}")
  unless body.is_a?(Hash) && body.key?("D")
    raise InvalidResponse, "The server response could not be understood"
  end
  response = ApiResponse.new body
  paging = response.pagination
  if paging.nil?
    results = response
  else
    q = CGI.parse(env[:url].query)
    if q.key?("_pagination") && q["_pagination"].first == "count"
      results = paging['TotalRows']
    else
      results = paginate_response(response, paging)
    end
  end
  case env[:status]
  when 400
    hash = {:message => response.message, :code => response.code, :status => env[:status]}

    # constraint violation
    if response.code == 1053
      details = body['D']['Details']
      hash[:details] = details
    end
    raise BadResourceRequest,hash
  when 401
    # Handle the WWW-Authenticate Response Header Field if present. This can be returned by 
    # OAuth2 implementations and wouldn't hurt to log.
    auth_header_error = env[:request_headers]["WWW-Authenticate"]
    SparkApi.logger.warn("Authentication error #{auth_header_error}") unless auth_header_error.nil?
    raise PermissionDenied, {:message => response.message, :code => response.code, :status => env[:status]}
  when 404
    raise NotFound, {:message => response.message, :code => response.code, :status => env[:status]}
  when 405
    raise NotAllowed, {:message => response.message, :code => response.code, :status => env[:status]}
  when 409
    raise BadResourceRequest, {:message => response.message, :code => response.code, :status => env[:status]}
  when 500
    raise ClientError, {:message => response.message, :code => response.code, :status => env[:status]}
  when 200..299
    SparkApi.logger.debug("Success!")
  else 
    raise ClientError, {:message => response.message, :code => response.code, :status => env[:status]}
  end
  env[:body] = results
end