Class: Whoosh::OpenAPI::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/whoosh/openapi/generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(title: "Whoosh API", version: "0.1.0", description: nil) ⇒ Generator

Returns a new instance of Generator.



8
9
10
11
12
13
# File 'lib/whoosh/openapi/generator.rb', line 8

def initialize(title: "Whoosh API", version: "0.1.0", description: nil)
  @title = title
  @version = version
  @description = description
  @paths = {}
end

Instance Method Details

#add_route(method:, path:, request_schema: nil, response_schema: nil, query_schema: nil, description: nil) ⇒ Object



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
# File 'lib/whoosh/openapi/generator.rb', line 15

def add_route(method:, path:, request_schema: nil, response_schema: nil, query_schema: nil, description: nil)
  openapi_path = path.gsub(/:(\w+)/, '{\1}')
  http_method = method.downcase.to_sym
  @paths[openapi_path] ||= {}
  operation = { summary: description || "#{method} #{path}" }

  params = path.scan(/:(\w+)/).flatten
  unless params.empty?
    operation[:parameters] = params.map { |p| { name: p, in: "path", required: true, schema: { type: "string" } } }
  end

  if query_schema
    qs = SchemaConverter.convert(query_schema)
    (qs[:properties] || {}).each do |name, prop|
      operation[:parameters] ||= []
      operation[:parameters] << {
        name: name.to_s, in: "query",
        required: qs[:required]&.include?(name) || false,
        schema: prop, description: prop[:description]
      }
    end
  end

  if request_schema
    operation[:requestBody] = {
      required: true,
      content: { "application/json" => { schema: SchemaConverter.convert(request_schema) } }
    }
  end

  operation[:responses] = { "200" => { description: "Successful response",
    content: { "application/json" => { schema: response_schema ? SchemaConverter.convert(response_schema) : { type: "object" } } } } }

  @paths[openapi_path][http_method] = operation
end

#generateObject



51
52
53
54
55
# File 'lib/whoosh/openapi/generator.rb', line 51

def generate
  spec = { openapi: "3.1.0", info: { title: @title, version: @version }, paths: @paths }
  spec[:info][:description] = @description if @description
  spec
end

#to_jsonObject



57
58
59
# File 'lib/whoosh/openapi/generator.rb', line 57

def to_json
  JSON.generate(generate)
end