Class: Rswag::Api::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rswag/api/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, config) ⇒ Middleware

Returns a new instance of Middleware.



8
9
10
11
# File 'lib/rswag/api/middleware.rb', line 8

def initialize(app, config)
  @app = app
  @config = config
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rswag/api/middleware.rb', line 13

def call(env)
  path = env['PATH_INFO']
  # Sanitize the filename for directory traversal by expanding, and ensuring
  # its starts with the root directory.
  openapi_root = @config.resolve_openapi_root(env)
  filename = File.expand_path(File.join(openapi_root, path))
  return @app.call(env) unless filename.start_with? openapi_root.to_s

  if env['REQUEST_METHOD'] == 'GET' && File.file?(filename)
    swagger = parse_file(filename)
    @config.swagger_filter.call(swagger, env) unless @config.swagger_filter.nil?
    mime = Rack::Mime.mime_type(::File.extname(path), 'text/plain')
    headers = { 'Content-Type' => mime }.merge(@config.swagger_headers || {})
    body = unload_swagger(filename, swagger)

    return [
      '200',
      headers,
      [body]
    ]
  end

  @app.call(env)
end