Class: Insights::API::Common::OpenApi::Generator
- Inherits:
-
Object
- Object
- Insights::API::Common::OpenApi::Generator
- Defined in:
- lib/insights/api/common/open_api/generator.rb
Constant Summary collapse
- PARAMETERS_PATH =
"/components/parameters".freeze
- SCHEMAS_PATH =
"/components/schemas".freeze
Instance Method Summary collapse
-
#api_version ⇒ Object
Let’s get the latest api version based on the openapi.json routes.
- #applicable_rails_routes ⇒ Object
- #base_path ⇒ Object
- #build_collection_schema(klass_name) ⇒ Object
- #build_parameter(name, value = nil) ⇒ Object
- #build_paths ⇒ Object
- #build_schema(klass_name) ⇒ Object
- #build_schema_error_not_found ⇒ Object
- #generator_blacklist_allowed_attributes ⇒ Object
- #generator_blacklist_attributes ⇒ Object
- #generator_blacklist_substitute_attributes ⇒ Object
- #generator_read_only_attributes ⇒ Object
- #generator_read_only_definitions ⇒ Object
- #handle_custom_route_action(_route_action, _verb, _primary_collection) ⇒ Object
-
#initialize ⇒ Generator
constructor
A new instance of Generator.
- #openapi_contents ⇒ Object
- #openapi_create_description(klass_name) ⇒ Object
- #openapi_destroy_description(klass_name) ⇒ Object
- #openapi_file ⇒ Object
- #openapi_list_description(klass_name, primary_collection) ⇒ Object
- #openapi_schema(klass_name) ⇒ Object
- #openapi_schema_properties(klass_name) ⇒ Object
- #openapi_schema_properties_value(klass_name, model, key, value) ⇒ Object
- #openapi_show_description(klass_name) ⇒ Object
- #openapi_tag_description(klass_name) ⇒ Object
- #openapi_untag_description(klass_name) ⇒ Object
- #openapi_update_description(klass_name, verb) ⇒ Object
- #parameters ⇒ Object
- #path_parts(openapi_path) ⇒ Object
- #rails_routes ⇒ Object
- #request_body(klass_name, action, single: true) ⇒ Object
- #run(graphql = false) ⇒ Object
- #schema_overrides ⇒ Object
- #schemas ⇒ Object
Constructor Details
#initialize ⇒ Generator
Returns a new instance of Generator.
46 47 48 49 50 51 |
# File 'lib/insights/api/common/open_api/generator.rb', line 46 def initialize app_prefix, app_name = base_path.match(/\A(.*)\/(.*)\/v\d+.\d+\z/).captures ENV['APP_NAME'] = app_name ENV['PATH_PREFIX'] = app_prefix Rails.application.reload_routes! end |
Instance Method Details
#api_version ⇒ Object
Let’s get the latest api version based on the openapi.json routes
17 18 19 20 21 22 23 24 |
# File 'lib/insights/api/common/open_api/generator.rb', line 17 def api_version @api_version ||= Rails.application.routes.routes.each_with_object([]) do |route, array| matches = ActionDispatch::Routing::RouteWrapper .new(route) .path.match(/\A.*\/v(\d+.\d+)\/openapi.json.*\z/) array << matches[1] if matches end.max end |
#applicable_rails_routes ⇒ Object
57 58 59 |
# File 'lib/insights/api/common/open_api/generator.rb', line 57 def applicable_rails_routes rails_routes.select { |i| i.path.start_with?(base_path) } end |
#base_path ⇒ Object
53 54 55 |
# File 'lib/insights/api/common/open_api/generator.rb', line 53 def base_path openapi_contents["servers"].first["variables"]["basePath"]["default"] end |
#build_collection_schema(klass_name) ⇒ Object
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# File 'lib/insights/api/common/open_api/generator.rb', line 243 def build_collection_schema(klass_name) collection_name = "#{klass_name.pluralize}Collection" schemas[collection_name] = { "type" => "object", "properties" => { "meta" => { "$ref" => "##{SCHEMAS_PATH}/CollectionMetadata" }, "links" => { "$ref" => "##{SCHEMAS_PATH}/CollectionLinks" }, "data" => { "type" => "array", "items" => { "$ref" => build_schema(klass_name) } } } } "##{SCHEMAS_PATH}/#{collection_name}" end |
#build_parameter(name, value = nil) ⇒ Object
192 193 194 195 |
# File 'lib/insights/api/common/open_api/generator.rb', line 192 def build_parameter(name, value = nil) parameters[name] = value "##{PARAMETERS_PATH}/#{name}" end |
#build_paths ⇒ Object
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
# File 'lib/insights/api/common/open_api/generator.rb', line 520 def build_paths applicable_rails_routes.each_with_object({}) do |route, expected_paths| without_format = route.path.split("(.:format)").first sub_path = without_format.split(base_path).last.sub(/:[_a-z]*id/, "{id}") route_destination = route.controller.split("/").last.camelize controller = "Api::V#{api_version.sub(".", "x")}::#{route_destination}Controller".safe_constantize klass_name = controller.try(:presentation_name) || route_destination.singularize verb = route.verb.downcase primary_collection = sub_path.split("/")[1].camelize.singularize expected_paths[sub_path] ||= {} expected_paths[sub_path][verb] = case route.action when "index" then openapi_list_description(klass_name, primary_collection) when "show" then openapi_show_description(klass_name) when "destroy" then openapi_destroy_description(klass_name) when "create" then openapi_create_description(klass_name) when "update" then openapi_update_description(klass_name, verb) when "tag" then openapi_tag_description(primary_collection) when "untag" then openapi_untag_description(primary_collection) else handle_custom_route_action(route.action.camelize, verb, primary_collection) end next if expected_paths[sub_path][verb] # If it's not generic action but a custom method like e.g. `post "order", :to => "service_plans#order"`, we will # try to take existing schema, because the description, summary, etc. are likely to be custom. expected_paths[sub_path][verb] = case verb when "post" if sub_path == "/graphql" && route.action == "query" schemas["GraphQLRequest"] = ::Insights::API::Common::GraphQL.openapi_graphql_request schemas["GraphQLResponse"] = ::Insights::API::Common::GraphQL.openapi_graphql_response ::Insights::API::Common::GraphQL.openapi_graphql_description else openapi_contents.dig("paths", sub_path, verb) || openapi_create_description(klass_name) end when "get" openapi_contents.dig("paths", sub_path, verb) || openapi_show_description(klass_name) else openapi_contents.dig("paths", sub_path, verb) end end end |
#build_schema(klass_name) ⇒ Object
108 109 110 111 |
# File 'lib/insights/api/common/open_api/generator.rb', line 108 def build_schema(klass_name) schemas[klass_name] = openapi_schema(klass_name) "##{SCHEMAS_PATH}/#{klass_name}" end |
#build_schema_error_not_found ⇒ Object
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
# File 'lib/insights/api/common/open_api/generator.rb', line 113 def build_schema_error_not_found klass_name = "ErrorNotFound" schemas[klass_name] = { "type" => "object", "properties" => { "errors" => { "type" => "array", "items" => { "type" => "object", "properties" => { "status" => { "type" => "integer", "example" => 404 }, "detail" => { "type" => "string", "example" => "Record not found" } } } } } } "##{SCHEMAS_PATH}/#{klass_name}" end |
#generator_blacklist_allowed_attributes ⇒ Object
499 500 501 |
# File 'lib/insights/api/common/open_api/generator.rb', line 499 def generator_blacklist_allowed_attributes @generator_blacklist_allowed_attributes ||= {} end |
#generator_blacklist_attributes ⇒ Object
490 491 492 493 494 495 496 497 |
# File 'lib/insights/api/common/open_api/generator.rb', line 490 def generator_blacklist_attributes @generator_blacklist_attributes ||= [ :resource_timestamp, :resource_timestamps, :resource_timestamps_max, :tenant_id, ].to_set.freeze end |
#generator_blacklist_substitute_attributes ⇒ Object
503 504 505 |
# File 'lib/insights/api/common/open_api/generator.rb', line 503 def generator_blacklist_substitute_attributes @generator_blacklist_substitute_attributes ||= {} end |
#generator_read_only_attributes ⇒ Object
507 508 509 510 511 512 513 514 |
# File 'lib/insights/api/common/open_api/generator.rb', line 507 def generator_read_only_attributes @generator_read_only_attributes ||= [ :archived_at, :created_at, :last_seen_at, :updated_at, ].to_set.freeze end |
#generator_read_only_definitions ⇒ Object
516 517 518 |
# File 'lib/insights/api/common/open_api/generator.rb', line 516 def generator_read_only_definitions @generator_read_only_definitions ||= [].to_set.freeze end |
#handle_custom_route_action(_route_action, _verb, _primary_collection) ⇒ Object
565 566 |
# File 'lib/insights/api/common/open_api/generator.rb', line 565 def handle_custom_route_action(_route_action, _verb, _primary_collection) end |
#openapi_contents ⇒ Object
40 41 42 43 44 |
# File 'lib/insights/api/common/open_api/generator.rb', line 40 def openapi_contents @openapi_contents ||= begin JSON.parse(File.read(openapi_file)) end end |
#openapi_create_description(klass_name) ⇒ Object
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
# File 'lib/insights/api/common/open_api/generator.rb', line 354 def openapi_create_description(klass_name) { "summary" => "Create a new #{klass_name}", "operationId" => "create#{klass_name}", "description" => "Creates a #{klass_name} object", "requestBody" => request_body(klass_name, "create"), "responses" => { "201" => { "description" => "#{klass_name} creation successful", "content" => { "application/json" => { "schema" => { "$ref" => build_schema(klass_name) } } } } } } end |
#openapi_destroy_description(klass_name) ⇒ Object
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/insights/api/common/open_api/generator.rb', line 287 def openapi_destroy_description(klass_name) { "summary" => "Delete an existing #{klass_name}", "operationId" => "delete#{klass_name}", "description" => "Deletes a #{klass_name} object", "parameters" => [{ "$ref" => build_parameter("ID") }], "responses" => { "204" => { "description" => "#{klass_name} deleted" }, "404" => { "description" => "Not found", "content" => { "application/json" => { "schema" => { "$ref" => build_schema_error_not_found } } } } } } end |
#openapi_file ⇒ Object
36 37 38 |
# File 'lib/insights/api/common/open_api/generator.rb', line 36 def openapi_file @openapi_file ||= Rails.root.join("public", "doc", "openapi-3-v#{api_version}.json").to_s end |
#openapi_list_description(klass_name, primary_collection) ⇒ Object
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
# File 'lib/insights/api/common/open_api/generator.rb', line 205 def openapi_list_description(klass_name, primary_collection) sub_collection = (primary_collection != klass_name) { "summary" => "List #{klass_name.pluralize}#{" for #{primary_collection}" if sub_collection}", "operationId" => "list#{primary_collection if sub_collection}#{klass_name.pluralize}", "description" => "Returns an array of #{klass_name} objects", "parameters" => [ { "$ref" => "##{PARAMETERS_PATH}/QueryLimit" }, { "$ref" => "##{PARAMETERS_PATH}/QueryOffset" }, { "$ref" => "##{PARAMETERS_PATH}/QueryFilter" }, { "$ref" => "##{PARAMETERS_PATH}/QuerySortBy" } ], "responses" => { "200" => { "description" => "#{klass_name.pluralize} collection", "content" => { "application/json" => { "schema" => { "$ref" => build_collection_schema(klass_name) } } } } } }.tap do |h| h["parameters"] << { "$ref" => build_parameter("ID") } if sub_collection next unless sub_collection h["responses"]["404"] = { "description" => "Not found", "content" => { "application/json" => { "schema" => { "$ref" => build_schema_error_not_found } } } } end end |
#openapi_schema(klass_name) ⇒ Object
197 198 199 200 201 202 203 |
# File 'lib/insights/api/common/open_api/generator.rb', line 197 def openapi_schema(klass_name) { "type" => "object", "properties" => openapi_schema_properties(klass_name), "additionalProperties" => false } end |
#openapi_schema_properties(klass_name) ⇒ Object
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
# File 'lib/insights/api/common/open_api/generator.rb', line 473 def openapi_schema_properties(klass_name) model = klass_name.constantize model.columns_hash.map do |key, value| unless (generator_blacklist_allowed_attributes[key.to_sym] || []).include?(klass_name) next if generator_blacklist_attributes.include?(key.to_sym) end if generator_blacklist_substitute_attributes.include?(key.to_sym) generator_blacklist_substitute_attributes[key.to_sym] else [key, openapi_schema_properties_value(klass_name, model, key, value)] end end.compact.sort.to_h rescue NameError openapi_contents["components"]["schemas"][klass_name]["properties"] end |
#openapi_schema_properties_value(klass_name, model, key, value) ⇒ Object
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/insights/api/common/open_api/generator.rb', line 412 def openapi_schema_properties_value(klass_name, model, key, value) if key == model.primary_key { "$ref" => "##{SCHEMAS_PATH}/ID" } elsif key.ends_with?("_id") properties_value = {} properties_value["$ref"] = if generator_read_only_definitions.include?(klass_name) # Everything under providers data is read only for now "##{SCHEMAS_PATH}/ID" else openapi_contents.dig(*path_parts(SCHEMAS_PATH), klass_name, "properties", key, "$ref") || "##{SCHEMAS_PATH}/ID" end properties_value else properties_value = { "type" => "string" } case value..type when :datetime properties_value["format"] = "date-time" when :integer properties_value["type"] = "integer" when :float properties_value["type"] = "number" when :boolean properties_value["type"] = "boolean" when :jsonb properties_value["type"] = "object" ['type', 'items', 'properties', 'additionalProperties'].each do |property_key| prop = openapi_contents.dig(*path_parts(SCHEMAS_PATH), klass_name, "properties", key, property_key) properties_value[property_key] = prop unless prop.nil? end end # Take existing attrs, that we won't generate ['example', 'format', 'readOnly', 'title', 'description'].each do |property_key| property_value = openapi_contents.dig(*path_parts(SCHEMAS_PATH), klass_name, "properties", key, property_key) properties_value[property_key] = property_value if property_value end if generator_read_only_definitions.include?(klass_name) || generator_read_only_attributes.include?(key.to_sym) # Everything under providers data is read only for now properties_value['readOnly'] = true end properties_value.sort.to_h end end |
#openapi_show_description(klass_name) ⇒ Object
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
# File 'lib/insights/api/common/open_api/generator.rb', line 260 def openapi_show_description(klass_name) { "summary" => "Show an existing #{klass_name}", "operationId" => "show#{klass_name}", "description" => "Returns a #{klass_name} object", "parameters" => [{ "$ref" => build_parameter("ID") }], "responses" => { "200" => { "description" => "#{klass_name} info", "content" => { "application/json" => { "schema" => { "$ref" => build_schema(klass_name) } } } }, "404" => { "description" => "Not found", "content" => { "application/json" => { "schema" => { "$ref" => build_schema_error_not_found } } } } } } end |
#openapi_tag_description(klass_name) ⇒ Object
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/insights/api/common/open_api/generator.rb', line 307 def openapi_tag_description(klass_name) { "summary" => "Tag a #{klass_name}", "operationId" => "tag#{klass_name}", "description" => "Tags a #{klass_name} object", "parameters" => [ { "$ref" => build_parameter("ID") } ], "requestBody" => request_body("Tag", "add", :single => false), "responses" => { "201" => { "description" => "#{klass_name} tagged successful", "content" => { "application/json" => { "schema" => { "type" => "array", "items" => { "$ref" => build_schema("Tag") } } } } }, "304" => { "description" => "Not modified" } } } end |
#openapi_untag_description(klass_name) ⇒ Object
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
# File 'lib/insights/api/common/open_api/generator.rb', line 337 def openapi_untag_description(klass_name) { "summary" => "Untag a #{klass_name}", "operationId" => "untag#{klass_name}", "description" => "Untags a #{klass_name} object", "parameters" => [ { "$ref" => build_parameter("ID") } ], "requestBody" => request_body("Tag", "removed", :single => false), "responses" => { "204" => { "description" => "#{klass_name} untagged successfully", } } } end |
#openapi_update_description(klass_name, verb) ⇒ Object
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
# File 'lib/insights/api/common/open_api/generator.rb', line 387 def openapi_update_description(klass_name, verb) action = verb == "patch" ? "Update" : "Replace" { "summary" => "#{action} an existing #{klass_name}", "operationId" => "#{action.downcase}#{klass_name}", "description" => "#{action}s a #{klass_name} object", "parameters" => [ { "$ref" => build_parameter("ID") } ], "requestBody" => request_body(klass_name, "update"), "responses" => { "204" => { "description" => "Updated, no content" }, "400" => { "description" => "Bad request" }, "404" => { "description" => "Not found", "content" => { "application/json" => { "schema" => { "$ref" => build_schema_error_not_found } } } } } } end |
#parameters ⇒ Object
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
# File 'lib/insights/api/common/open_api/generator.rb', line 141 def parameters @parameters ||= { "QueryFilter" => { "in" => "query", "name" => "filter", "description" => "Filter for querying collections.", "required" => false, "style" => "deepObject", "explode" => true, "schema" => { "type" => "object" } }, "QueryLimit" => { "in" => "query", "name" => "limit", "description" => "The numbers of items to return per page.", "required" => false, "schema" => { "type" => "integer", "minimum" => 1, "maximum" => 1000, "default" => 100 } }, "QueryOffset" => { "in" => "query", "name" => "offset", "description" => "The number of items to skip before starting to collect the result set.", "required" => false, "schema" => { "type" => "integer", "minimum" => 0, "default" => 0 } }, "QuerySortBy" => { "in" => "query", "name" => "sort_by", "description" => "The list of attribute and order to sort the result set by.", "required" => false, "schema" => { "oneOf" => [ { "$ref" => "##{SCHEMAS_PATH}/SortByAttribute" }, { "type" => "array", "items" => { "$ref" => "##{SCHEMAS_PATH}/SortByAttribute" } } ] } } } end |
#path_parts(openapi_path) ⇒ Object
12 13 14 |
# File 'lib/insights/api/common/open_api/generator.rb', line 12 def path_parts(openapi_path) openapi_path.split("/")[1..-1] end |
#rails_routes ⇒ Object
26 27 28 29 30 31 32 33 34 |
# File 'lib/insights/api/common/open_api/generator.rb', line 26 def rails_routes Rails.application.routes.routes.each_with_object([]) do |route, array| r = ActionDispatch::Routing::RouteWrapper.new(route) next if r.internal? # Don't display rails routes next if r.engine? # Don't care right now... array << r end end |
#request_body(klass_name, action, single: true) ⇒ Object
373 374 375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/insights/api/common/open_api/generator.rb', line 373 def request_body(klass_name, action, single: true) schema = single ? { "$ref" => build_schema(klass_name) } : {"type" => "array", "items" => {"$ref" => build_schema(klass_name)}} { "content" => { "application/json" => { "schema" => schema } }, "description" => "#{klass_name} attributes to #{action}", "required" => true } end |
#run(graphql = false) ⇒ Object
463 464 465 466 467 468 469 470 471 |
# File 'lib/insights/api/common/open_api/generator.rb', line 463 def run(graphql = false) new_content = openapi_contents.dup new_content["paths"] = build_paths.sort.to_h new_content["components"] ||= {} new_content["components"]["schemas"] = schemas.merge(schema_overrides).sort.each_with_object({}) { |(name, val), h| h[name] = val || openapi_contents["components"]["schemas"][name] || {} } new_content["components"]["parameters"] = parameters.sort.each_with_object({}) { |(name, val), h| h[name] = val || openapi_contents["components"]["parameters"][name] || {} } File.write(openapi_file, JSON.pretty_generate(new_content) + "\n") Insights::API::Common::GraphQL::Generator.generate(api_version, new_content) if graphql end |
#schema_overrides ⇒ Object
568 569 570 |
# File 'lib/insights/api/common/open_api/generator.rb', line 568 def schema_overrides {} end |
#schemas ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/insights/api/common/open_api/generator.rb', line 61 def schemas @schemas ||= { "CollectionLinks" => { "type" => "object", "properties" => { "first" => { "type" => "string" }, "last" => { "type" => "string" }, "next" => { "type" => "string" }, "prev" => { "type" => "string" }, } }, "CollectionMetadata" => { "type" => "object", "properties" => { "count" => { "type" => "integer" }, "limit" => { "type" => "integer" }, "offset" => { "type" => "integer" } } }, "ID" => { "type" => "string", "description" => "ID of the resource", "pattern" => "^\\d+$", "readOnly" => true, }, "SortByAttribute" => { "type" => "string", "description" => "Attribute with optional order to sort the result set by.", "pattern" => "^[a-z\\-_]+(:asc|:desc)?$" } } end |