Class: ActionSpec::OpenApi::Schema

Inherits:
Object
  • Object
show all
Defined in:
lib/action_spec/open_api/schema.rb

Constant Summary collapse

LOCATION_MAP =
{
  header: "header",
  path: "path",
  query: "query",
  cookie: "cookie"
}.freeze
MEDIA_TYPE_MAP =
{
  json: "application/json",
  form: "multipart/form-data"
}.freeze

Instance Method Summary collapse

Instance Method Details

#parameter(field, location:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/action_spec/open_api/schema.rb', line 18

def parameter(field, location:)
  {
    "name" => parameter_name(field, location),
    "in" => LOCATION_MAP.fetch(location),
    "required" => location == :path ? true : field.required?,
    "schema" => schema_for(field.schema)
  }.tap do |parameter|
    if (description = field.schema.description).present?
      parameter["description"] = description
    end
  end
end

#request_body(request) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/action_spec/open_api/schema.rb', line 31

def request_body(request)
  content = request.body_media_types.each_with_object(ActiveSupport::OrderedHash.new) do |(media_type, fields), hash|
    hash[MEDIA_TYPE_MAP.fetch(media_type, media_type.to_s)] = {
      "schema" => object_schema(fields.fields)
    }
  end
  return if content.empty?

  { "content" => content }.tap do |body|
    body["required"] = true if request.body_required?
  end
end

#response(response) ⇒ Object



44
45
46
47
48
49
# File 'lib/action_spec/open_api/schema.rb', line 44

def response(response)
  {
    "description" => response.description.presence || "OK",
    "content" => response_content(response).presence
  }.compact
end

#schema_for(schema) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/action_spec/open_api/schema.rb', line 51

def schema_for(schema)
  case schema
  when ActionSpec::Schema::Scalar then scalar_schema(schema)
  when ActionSpec::Schema::ObjectOf then object_schema(schema.fields.values, schema:)
  when ActionSpec::Schema::ArrayOf then array_schema(schema)
  else { "type" => "string" }
  end
end