class Restforce::Middleware::JsonResponse

rubocop:disable Style/ClassAndModuleChildren

Constants

CONTENT_TYPE

This is the only line that differs substantively from the version in Faraday. In Faraday, this refers to a Faraday constant.

Public Class Methods

new(app = nil, parser_options: nil, content_type: /\bjson$/, preserve_raw: false) click to toggle source
Calls superclass method
# File lib/restforce/middleware/json_response.rb, line 22
def initialize(app = nil, parser_options: nil, content_type: /\bjson$/,
               preserve_raw: false)
  super(app)
  @parser_options = parser_options
  @content_types = Array(content_type)
  @preserve_raw = preserve_raw
end

Public Instance Methods

call(env) click to toggle source

Taken from ‘lib/faraday/middleware.rb` in the `faraday` gem (<github.com/lostisland/faraday/blob/08b7d4d/lib/faraday/middleware.rb>), with a tiny adaptation to refer to the `@app` instance variable rather than expecting an `attr_reader` to exist.

In Faraday versions before v1.2.0, ‘#call` is missing.

Copyright © 2009-2022 Rick Olson, Zack Hobson Licensed under the MIT License.

# File lib/restforce/middleware/json_response.rb, line 41
def call(env)
  on_request(env) if respond_to?(:on_request)
  @app.call(env).on_complete do |environment|
    on_complete(environment) if respond_to?(:on_complete)
  end
end
on_complete(env) click to toggle source
# File lib/restforce/middleware/json_response.rb, line 48
def on_complete(env)
  process_response(env) if parse_response?(env)
end

Private Instance Methods

parse(body) click to toggle source
# File lib/restforce/middleware/json_response.rb, line 61
def parse(body)
  ::JSON.parse(body, @parser_options || {}) unless body.strip.empty?
end
parse_response?(env) click to toggle source
# File lib/restforce/middleware/json_response.rb, line 65
def parse_response?(env)
  process_response_type?(env) &&
    env[:body].respond_to?(:to_str)
end
process_response(env) click to toggle source
# File lib/restforce/middleware/json_response.rb, line 54
def process_response(env)
  env[:raw_body] = env[:body] if @preserve_raw
  env[:body] = parse(env[:body])
rescue StandardError, SyntaxError => e
  raise Faraday::ParsingError.new(e, env[:response])
end
process_response_type?(env) click to toggle source
# File lib/restforce/middleware/json_response.rb, line 70
def process_response_type?(env)
  type = response_type(env)
  @content_types.empty? || @content_types.any? do |pattern|
    pattern.is_a?(Regexp) ? type.match?(pattern) : type == pattern
  end
end
response_type(env) click to toggle source
# File lib/restforce/middleware/json_response.rb, line 77
def response_type(env)
  type = env[:response_headers][CONTENT_TYPE].to_s
  type = type.split(';', 2).first if type.index(';')
  type
end