Class: OpenapiFirst::Router

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

Constant Summary collapse

RAW_PATH_PARAMS =

The unconverted path parameters before they are converted to the types defined in the API description

'openapi.raw_path_params'
NOT_FOUND =
Rack::Response.new('Not Found', 404).finish.freeze
METHOD_NOT_ALLOWED =
Rack::Response.new('Method Not Allowed', 405).finish.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, options) ⇒ Router

Returns a new instance of Router.



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

def initialize(
  app,
  options
)
  @app = app
  @raise = options.fetch(:raise_error, false)
  @not_found = options.fetch(:not_found, :halt)
  @error_response_class = options.fetch(:error_response, Config.default_options.error_response)
  spec = options.fetch(:spec)
  raise "You have to pass spec: when initializing #{self.class}" unless spec

  @definition = spec.is_a?(Definition) ? spec : OpenapiFirst.load(spec)
  @filepath = @definition.filepath
end

Instance Method Details

#call(env) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/openapi_first/router.rb', line 31

def call(env)
  env[OPERATION] = nil
  request = Rack::Request.new(env)
  path_item, path_params = @definition.find_path_item_and_params(request.path)
  operation = path_item&.find_operation(request.request_method.downcase)

  env[OPERATION] = operation
  env[RAW_PATH_PARAMS] = path_params

  if operation.nil?
    raise_error(env) if @raise
    return @app.call(env) if @not_found == :continue
  end

  return NOT_FOUND unless path_item
  return METHOD_NOT_ALLOWED unless operation

  @app.call(env)
end