# frozen_string_literal: true # typed: true require "json" # Class to build Swagger json description of entities class SwaggerBuilder class << self def build_swagger_for(models, host_with_port) doc = {} doc["swagger"] = "2.0" doc["info"] = build_info(models) doc["host"] = host_with_port doc["schemes"] = "http" doc["basePath"] = "/#{ENV["base_path"]}" doc["paths"] = generate_paths_for models JSON.generate(doc) end def build_info(models) info = {} info["description"] = "Schemaless REST API providing CRUD for #{models.keys.length} models: #{models.keys.join("\n")}" info end def generate_paths_for(models) paths = { "/" => summary } models.each_key do |model| paths["/#{model.downcase}"] = model_paths(model) paths["/#{model.downcase}/{modelId}"] = paths_at_id(model) end paths end def summary { get: { responses: { "200": { "description": "Basic basic summary of API - could be used as health check" } } } } end def model_paths(model) { post: { parameters: any_json_request, responses: { "201": { "description": "Response with id of created #{model}" } } }, get: { parameters: [ { name: "params", description: "Any key can be used to filter #{model} by", schema: { type: "object", # If the parameter values are of specific type, e.g. string: additionalProperties: { type: "string" } } } ], responses: { "200": { "description": "List of all #{model} objects" } } } } end def any_json_request [ { "description": "Arbitrary JSON object payload", "in": "body", "name": "body", "required": true, "schema": { "type": "object" } } ] end def paths_at_id(model) { get: { description: "Data of #{model} at passed id", parameters: id_params(model), responses: { "200": { "description": "Data of #{model} requested" }, "404": { "description": "#{model} not found" } } }, put: { description: "Update id of #{model} to be provided data", parameters: [ { "description": "Arbitrary JSON object payload", "in": "body", "name": "body", "required": true, "schema": { "type": "object" } }, { "name": "modelId", "in": "path", "description": "ID of #{model} to update", "required": true, "type": "string" } ], responses: { "204": { "description": "Response" }, "404": { "description": "#{model} not found" } } }, delete: { description: "Delete #{model} at passed id", parameters: id_params(model), responses: { "204": { "description": "Response" }, "404": { "description": "#{model} not found" } } } } end def id_params(model) [ { "name": "modelId", "in": "path", "description": "ID of #{model} to return", "required": true, "type": "string" } ] end end end