Class: OpenapiRuby::Middleware::ResponseValidation

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_ruby/middleware/response_validation.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ ResponseValidation

Returns a new instance of ResponseValidation.



6
7
8
9
10
11
12
# File 'lib/openapi_ruby/middleware/response_validation.rb', line 6

def initialize(app, options = {})
  @app = app
  @resolver = options[:schema_resolver] || SchemaResolver.new(spec_path: options[:spec_path])
  @error_handler = options[:error_handler] || ErrorHandler.new
  @mode = options.fetch(:mode, OpenapiRuby.configuration.response_validation)
  @validate_success_only = options.fetch(:validate_success_only, true)
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
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
# File 'lib/openapi_ruby/middleware/response_validation.rb', line 14

def call(env)
  return @app.call(env) if @mode == :disabled

  status, headers, body = @app.call(env)

  # Skip validation for certain status codes
  return [status, headers, body] if skip_validation?(status)

  operation = env["openapi_ruby.operation"]
  unless operation
    request = Rack::Request.new(env)
    result = @resolver.find_operation(request.request_method, request.path_info)
    operation = result[:operation] if result
  end
  return [status, headers, body] unless operation

  # Find the response spec
  response_spec = operation.dig("responses", status.to_s) ||
    operation.dig("responses", "default")
  return [status, headers, body] unless response_spec

  # Validate the response body
  response_body = read_body(body)
  errors = validate_response(response_spec, response_body)

  if errors.any?
    if @mode == :warn_only
      env["openapi_ruby.response_errors"] = errors
      warn "[openapi_ruby] Response validation warnings: #{errors.join(", ")}"
    else
      return @error_handler.invalid_response(errors)
    end
  end

  [status, headers, body]
end