Class: Common::Client::Middleware::Response::JsonParser

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/common/client/middleware/response/json_parser.rb

Constant Summary collapse

WHITESPACE_REGEX =
/\A^\s*$\z/
MHV_SUCCESS_REGEX =
/^success/i
UNPARSABLE_STATUS_CODES =
[204, 301, 302, 304].freeze

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/common/client/middleware/response/json_parser.rb', line 12

def on_complete(env)
  if env.response_headers['content-type']&.match?(/\bjson/)
    if env.body =~ WHITESPACE_REGEX || env.body =~ MHV_SUCCESS_REGEX
      env.body = ''
    else
      env.body = parse(env.body) unless UNPARSABLE_STATUS_CODES.include?(env[:status])
    end
  end
end

#parse(body = nil) ⇒ Object



22
23
24
25
26
# File 'lib/common/client/middleware/response/json_parser.rb', line 22

def parse(body = nil)
  Oj.load(body)
rescue Oj::Error => e
  raise Common::Client::Errors::Serialization, e
end