Class: OpenapiFirst::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_first/builder.rb

Overview

Builds parts of a Definition This knows how to read a resolved OpenAPI document and build Request and Response objects.

Constant Summary collapse

REQUEST_METHODS =

rubocop:disable Metrics/ClassLength

%w[get head post put patch delete trace options].freeze
ParsedParameters =
Data.define(:path, :query, :header, :cookie, :path_schema, :query_schema, :header_schema,
:cookie_schema)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(contents, filepath:, config:) ⇒ Builder

Returns a new instance of Builder.



20
21
22
23
24
25
26
27
# File 'lib/openapi_first/builder.rb', line 20

def initialize(contents, filepath:, config:)
  @schemer_configuration = JSONSchemer::Configuration.new(
    meta_schema: detect_meta_schema(contents, filepath),
    insert_property_defaults: true
  )
  @config = config
  @contents = RefResolver.for(contents, dir: filepath && File.dirname(filepath))
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



29
30
31
# File 'lib/openapi_first/builder.rb', line 29

def config
  @config
end

Class Method Details

.build_router(contents, filepath:, config:) ⇒ Object

Builds a router from a resolved OpenAPI document.

Parameters:



16
17
18
# File 'lib/openapi_first/builder.rb', line 16

def self.build_router(contents, filepath:, config:)
  new(contents, filepath:, config:).router
end

Instance Method Details

#build_headers_schema(headers_object) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/openapi_first/builder.rb', line 164

def build_headers_schema(headers_object)
  return unless headers_object&.any?

  properties = {}
  required = []
  headers_object.each do |name, header|
    schema = header['schema']
    next if name.casecmp('content-type').zero?

    properties[name] = schema if schema
    required << name if header['required']
  end
  {
    'properties' => properties,
    'required' => required
  }
end

#build_parameter_schema(parameters) ⇒ Object



101
102
103
104
105
106
107
# File 'lib/openapi_first/builder.rb', line 101

def build_parameter_schema(parameters)
  schema = build_parameters_schema(parameters)

  JSONSchemer.schema(schema,
                     configuration: schemer_configuration,
                     after_property_validation: config.hooks[:after_request_parameter_property_validation])
end

#build_parameters_schema(parameters) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/openapi_first/builder.rb', line 182

def build_parameters_schema(parameters)
  return unless parameters

  properties = {}
  required = []
  parameters.each do |parameter|
    schema = parameter['schema']
    name = parameter['name']
    properties[name] = schema if schema
    required << name if parameter['required']
  end

  {
    'properties' => properties,
    'required' => required
  }
end

#build_requests(path:, request_method:, operation_object:, parameters:) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/openapi_first/builder.rb', line 109

def build_requests(path:, request_method:, operation_object:, parameters:)
  required_body = operation_object['requestBody']&.resolved&.fetch('required', false) == true
  result = operation_object.dig('requestBody', 'content')&.map do |content_type, content_object|
    content_schema = content_object['schema'].schema(
      configuration: schemer_configuration,
      after_property_validation: config.hooks[:after_request_body_property_validation]
    )
    Request.new(path:, request_method:,
                operation_object: operation_object.resolved,
                parameters:, content_type:,
                content_schema:,
                required_body:)
  end || []
  return result if required_body

  result << Request.new(
    path:, request_method:, operation_object: operation_object.resolved,
    parameters:, content_type: nil, content_schema: nil,
    required_body:
  )
end

#build_responses(responses:) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/openapi_first/builder.rb', line 131

def build_responses(responses:)
  return [] unless responses

  responses.flat_map do |status, response_object|
    headers = response_object['headers']&.resolved
    headers_schema = JSONSchemer::Schema.new(
      build_headers_schema(headers),
      configuration: schemer_configuration
    )
    response_object['content']&.map do |content_type, content_object|
      content_schema = content_object['schema'].schema(configuration: schemer_configuration)
      Response.new(status:,
                   headers:,
                   headers_schema:,
                   content_type:,
                   content_schema:)
    end || Response.new(status:, headers:, headers_schema:, content_type: nil,
                        content_schema: nil)
  end
end

#detect_meta_schema(document, filepath) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/openapi_first/builder.rb', line 32

def detect_meta_schema(document, filepath)
  # Copied from JSONSchemer 🙇🏻‍♂️
  version = document['openapi']
  case version
  when /\A3\.1\.\d+\z/
    @document_schema = JSONSchemer.openapi31_document
    document.fetch('jsonSchemaDialect') { JSONSchemer::OpenAPI31::BASE_URI.to_s }
  when /\A3\.0\.\d+\z/
    @document_schema = JSONSchemer.openapi30_document
    JSONSchemer::OpenAPI30::BASE_URI.to_s
  else
    raise Error, "Unsupported OpenAPI version #{version.inspect} #{filepath}"
  end
end

#group_parameters(parameter_definitions) ⇒ Object



155
156
157
158
159
160
161
162
# File 'lib/openapi_first/builder.rb', line 155

def group_parameters(parameter_definitions)
  result = {}
  parameter_definitions&.each do |parameter|
    (result[parameter['in'].to_sym] ||= []) << parameter
  end
  result[:header]&.reject! { IGNORED_HEADER_PARAMETERS.include?(_1['name']) }
  result
end

#parse_parameters(parameters) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/openapi_first/builder.rb', line 79

def parse_parameters(parameters)
  grouped_parameters = group_parameters(parameters)
  ParsedParameters.new(
    query: grouped_parameters[:query],
    path: grouped_parameters[:path],
    cookie: grouped_parameters[:cookie],
    header: grouped_parameters[:header],
    query_schema: build_parameter_schema(grouped_parameters[:query]),
    path_schema: build_parameter_schema(grouped_parameters[:path]),
    cookie_schema: build_parameter_schema(grouped_parameters[:cookie]),
    header_schema: build_parameter_schema(grouped_parameters[:header])
  )
end

#resolve_parameters(parameters) ⇒ Object



93
94
95
96
97
98
99
# File 'lib/openapi_first/builder.rb', line 93

def resolve_parameters(parameters)
  parameters&.map do |parameter|
    result = parameter.resolved
    result['schema'] = parameter['schema'].resolved
    result
  end.to_a
end

#routerObject

rubocop:disable Metrics/MethodLength



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
# File 'lib/openapi_first/builder.rb', line 47

def router # rubocop:disable Metrics/MethodLength
  router = OpenapiFirst::Router.new
  @contents.fetch('paths').each do |path, path_item_object|
    path_parameters = resolve_parameters(path_item_object['parameters'])
    path_item_object.resolved.keys.intersection(REQUEST_METHODS).map do |request_method|
      operation_object = path_item_object[request_method]
      operation_parameters = resolve_parameters(operation_object['parameters'])
      parameters = parse_parameters(operation_parameters.chain(path_parameters))

      build_requests(path:, request_method:, operation_object:,
                     parameters:).each do |request|
        router.add_request(
          request,
          request_method:,
          path:,
          content_type: request.content_type
        )
      end
      build_responses(responses: operation_object['responses']).each do |response|
        router.add_response(
          response,
          request_method:,
          path:,
          status: response.status,
          response_content_type: response.content_type
        )
      end
    end
  end
  router
end