Class: Miniswag::Api::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app, config) ⇒ Middleware

Returns a new instance of Middleware.



10
11
12
13
# File 'lib/miniswag/api/middleware.rb', line 10

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

Instance Method Details

#call(env) ⇒ Object



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

def call(env)
  path = env['PATH_INFO']
  # Sanitize the filename for directory traversal by expanding, and ensuring
  # it 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)
    openapi = parse_file(filename)
    @config.openapi_filter&.call(openapi, env)
    mime = Rack::Mime.mime_type(::File.extname(path), 'text/plain')
    headers = { 'Content-Type' => mime }.merge(@config.openapi_headers || {})
    body = unload_openapi(filename, openapi)

    return [200, headers, [body]]
  end

  @app.call(env)
end