Class: OpenapiRuby::Middleware::RequestValidation

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of RequestValidation.



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

def initialize(app, options = {})
  @app = app
  @resolver = options[:schema_resolver] || SchemaResolver.new(spec_path: options[:spec_path])
  @strict = options.fetch(:strict, false)
  @coerce = options.fetch(:coerce, OpenapiRuby.configuration.coerce_params)
  @error_handler = options[:error_handler] || ErrorHandler.new
  @mode = options.fetch(:mode, OpenapiRuby.configuration.request_validation)
  @prefix = options[:prefix]
end

Instance Method Details

#call(env) ⇒ Object



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
58
59
60
61
# File 'lib/openapi_ruby/middleware/request_validation.rb', line 16

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

  # Strip prefix for path matching
  match_path = @prefix ? request.path_info.sub(@prefix, "") : request.path_info
  result = @resolver.find_operation(request.request_method, match_path)

  if result.nil?
    return strict? ? @error_handler.not_found(request.path_info) : @app.call(env)
  end

  operation = result[:operation]
  path_params = result[:path_params]
  parameters = operation.fetch("parameters", [])

  # Coerce params if enabled
  if @coerce
    env["rack.request.query_hash"] = Coercion.coerce_params(
      request.GET, parameters.select { |p| p["in"] == "query" }
    )
  end

  # Store operation info for downstream use
  env["openapi_ruby.operation"] = operation
  env["openapi_ruby.path_params"] = path_params
  env["openapi_ruby.path_template"] = result[:template]

  # Validate request
  errors = validate_request(request, operation, path_params)

  if errors.any?
    return @error_handler.invalid_request(errors) unless @mode == :warn_only

    env["openapi_ruby.request_errors"] = errors
    warn "[openapi_ruby] Request validation warnings: #{errors.join(", ")}"
  end

  @app.call(env)
end