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
13
# 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)
  @prefix = options[:prefix]
end

Instance Method Details

#call(env) ⇒ Object



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
50
51
52
53
54
55
56
57
# File 'lib/openapi_ruby/middleware/response_validation.rb', line 15

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

  request = Rack::Request.new(env)

  # Skip if request doesn't match prefix
  if @prefix && !request.path_info.start_with?(@prefix)
    return @app.call(env)
  end

  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