Class: OpenApiRack::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



3
4
5
6
7
# File 'lib/open_api_rack/middleware.rb', line 3

def initialize(app)
  @app = app

  @headers_list = OpenApiRack.configuration.headers_list
end

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/open_api_rack/middleware.rb', line 9

def call(env)
  app_call_result = @app.call(env)

  return app_call_result if skip?(env)

  if File.exist?("public/open-api.yaml")
    open_api_hash = YAML.load_file("public/open-api.yaml")
  else
    open_api_hash = {
      "openapi" => "3.0.0",
      "info" => {
        "title" => "client_area",
        "version" => "1.0.0"
      },
      "servers" => [
        {"url" => "http://localhost:3000"}
      ],
      "paths" => {}
    }
  end

  open_api_hash["paths"].merge!(
    env["PATH_INFO"] => {
      env["REQUEST_METHOD"].downcase => {
        "parameters" => Rack::Request.new(env).params.map do |k, v|
          {
            "name" => k,
            "in" => "query",
            "schema" => {
              "type" => "string"
            },
            "required" => false,
            "example" => v
          }
        end.concat(
          @headers_list.map do |k|
            {
              "name" => k,
              "in" => "header",
              "schema" => {
                "type" => "string"
              },
              "required" => false,
              "example" => env["HTTP_#{k.to_s.upcase}"]
            }
          end
        ),
        "responses" => {
          app_call_result[0] => {
            "description" => "OK",
            "content" => {
              "application/json" => {
                "schema" => {
                  "type" => "object",
                  "properties" => parse_json(response_body(app_call_result))
                }
              }
            },
            "headers" => response_headers(app_call_result)
          }
        }
      }.merge(parsed_request_body(env))
    }
  )

  File.open('public/open-api.yaml', 'w') do |f|
    f.write(open_api_hash.to_yaml)
  end

  app_call_result
end