Class: Graphiti::OpenAPI::Generator

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Dry::Core::Memoizable
Defined in:
app/models/graphiti/open_api/generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root: Rails.root, schema: root.join("public#{ApplicationResource.endpoint_namespace}").join("schema.json"), jsonapi: root.join("public/schemas/jsonapi.json"), template: root.join("config/openapi.yml")) ⇒ Generator

Returns a new instance of Generator.



12
13
14
15
16
17
18
19
20
21
# File 'app/models/graphiti/open_api/generator.rb', line 12

def initialize(
               root: Rails.root,
               schema: root.join("public#{ApplicationResource.endpoint_namespace}").join("schema.json"),
               jsonapi: root.join("public/schemas/jsonapi.json"),
               template: root.join("config/openapi.yml"))
  @root = Pathname(root)
  @schema_path = schema
  @jsonapi_path = jsonapi
  @template_path = template
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



27
28
29
# File 'app/models/graphiti/open_api/generator.rb', line 27

def root
  @root
end

#schema{String => Source} (readonly)

Returns:



27
# File 'app/models/graphiti/open_api/generator.rb', line 27

attr_reader :root

Instance Method Details

#pathsObject



45
46
47
48
# File 'app/models/graphiti/open_api/generator.rb', line 45

def paths
  @paths ||=
    endpoints.values.map(&:paths).inject(&:merge)
end

#schema_source(path = @schema_path) ⇒ Object



37
38
39
# File 'app/models/graphiti/open_api/generator.rb', line 37

def schema_source(path = @schema_path)
  Source.load(path)
end

#template_source(path = @template_path) ⇒ Object



41
42
43
# File 'app/models/graphiti/open_api/generator.rb', line 41

def template_source(path = @template_path)
  Source.load(path, parse: YAML.method(:safe_load))
end

#to_openapi(format: :json) ⇒ Object



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
# File 'app/models/graphiti/open_api/generator.rb', line 50

def to_openapi(format: :json)
  template = template_source.data
  data = {
    openapi: "3.0.1",
    servers: servers,
    tags: tags,
    paths: paths,
    components: {
      schemas: schemas,
      parameters: parameters,
      requestBodies: request_bodies,
      responses: responses,
      links: links,
    },
  }
  specification = Functions[:deep_merge][template, data]
  case format
  when :json
    specification
  when :yaml
    json = specification.to_json
    JSON.parse(json).to_yaml.gsub(/\A---\s+/, '')
  else
    raise ArgumentError, "Unknown format: `#{format.inspect}`"
  end
end