Class: OpenapiFirst::OperationResolver

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

Constant Summary collapse

NOT_FOUND =
Rack::Response.new('', 404).finish.freeze
DEFAULT_APP =
->(_env) { NOT_FOUND }

Instance Method Summary collapse

Constructor Details

#initialize(app = DEFAULT_APP, namespace:) ⇒ OperationResolver

Returns a new instance of OperationResolver.



10
11
12
13
# File 'lib/openapi_first/operation_resolver.rb', line 10

def initialize(app = DEFAULT_APP, namespace:)
  @app = app
  @namespace = namespace
end

Instance Method Details

#call(env) ⇒ Object

rubocop:disable Metrics/AbcSize



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

def call(env) # rubocop:disable Metrics/AbcSize
  operation = env[OpenapiFirst::OPERATION]
  return @app.call(env) unless operation

  operation_id = operation.operation_id
  res = Rack::Response.new
  params = build_params(env)
  handler = find_handler(operation_id)
  result = handler.call(params, res)
  res.write MultiJson.dump(result) if result && res.body.empty?
  res[Rack::CONTENT_TYPE] ||= find_content_type(operation, res.status)
  res.finish
end

#find_handler(operation_id) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/openapi_first/operation_resolver.rb', line 29

def find_handler(operation_id)
  if operation_id.include?('.')
    module_name, method_name = operation_id.split('.')
    return @namespace.const_get(module_name.camelize).method(method_name)
  end

  if operation_id.include?('#')
    module_name, class_name = operation_id.split('#')
    return @namespace.const_get(module_name.camelize)
                     .const_get(class_name.camelize).new
  end
  @namespace.method(operation_id)
end