Class: OpenapiFirst::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_first/router.rb

Constant Summary collapse

NOT_FOUND =
Rack::Response.new('', 404).finish.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, spec:, allow_unknown_operation: false) ⇒ Router

Returns a new instance of Router.



12
13
14
15
16
# File 'lib/openapi_first/router.rb', line 12

def initialize(app, spec:, allow_unknown_operation: false)
  @app = app
  @spec = spec
  @allow_unknown_operation = allow_unknown_operation
end

Instance Method Details

#call(env) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/openapi_first/router.rb', line 18

def call(env)
  req = Rack::Request.new(env)
  operation = env[OPERATION] = @spec.find_operation(req)
  path_params = find_path_params(operation, req)
  env[PATH_PARAMS] = path_params if path_params
  return @app.call(env) if operation || @allow_unknown_operation

  NOT_FOUND
end

#find_path_params(operation, req) ⇒ Object



28
29
30
31
32
33
# File 'lib/openapi_first/router.rb', line 28

def find_path_params(operation, req)
  return unless operation&.path_parameters&.any?

  pattern = Mustermann::Template.new(operation.path.path)
  pattern.params(req.path)
end