Class: Whoosh::OpenAPI::SchemaConverter

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

Constant Summary collapse

TYPE_MAP =
{
  "String" => "string", "Integer" => "integer", "Float" => "number",
  "Hash" => "object", "Array" => "array", "Time" => "string", "DateTime" => "string"
}.freeze

Class Method Summary collapse

Class Method Details

.convert(schema_class) ⇒ Object



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

def self.convert(schema_class)
  return {} unless schema_class.respond_to?(:fields)
  properties = {}
  required = []

  schema_class.fields.each do |name, opts|
    type = opts[:type]
    if type.is_a?(Class) && type < Schema
      properties[name] = convert(type)
    else
      prop = { type: type_for(type) }
      prop[:description] = opts[:desc] if opts[:desc]
      prop[:default] = opts[:default] if opts.key?(:default)
      prop[:minimum] = opts[:min] if opts[:min]
      prop[:maximum] = opts[:max] if opts[:max]
      prop[:format] = "date-time" if type == Time || type == DateTime
      properties[name] = prop
    end
    required << name if opts[:required]
  end

  result = { type: "object", properties: properties }
  result[:required] = required unless required.empty?
  result
end

.type_for(type) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/whoosh/openapi/schema_converter.rb', line 37

def self.type_for(type)
  # Check for Dry::Types (Bool)
  begin
    return "boolean" if type.is_a?(Dry::Types::Type)
  rescue
    # ignore if Dry::Types not available
  end
  TYPE_MAP[type.to_s] || "string"
end