verquest 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,26 +15,29 @@ module Verquest
15
15
  # @param version [String, nil] Specific version to use, defaults to configuration setting
16
16
  # @param validate [Boolean, nil] Whether to validate the params, defaults to configuration setting
17
17
  # @param remove_extra_root_keys [Boolean, nil] Whether to remove extra keys at the root level, defaults to configuration setting
18
+ # @param reject_other_version_keys [Boolean, nil] Whether to report root keys only another version declares as validation errors (only when validating), defaults to configuration setting
18
19
  # @return [Verquest::Result, Hash] When validation_error_handling is :result, returns a Success result with mapped params or Failure result with validation errors.
19
20
  # When validation_error_handling is :raise, returns mapped params directly or raises InvalidParamsError with validation errors.
20
- def process(params, version: nil, validate: nil, remove_extra_root_keys: nil)
21
+ def process(params, version: nil, validate: nil, remove_extra_root_keys: nil, reject_other_version_keys: nil)
21
22
  validate = Verquest.configuration.validate_params if validate.nil?
22
23
  remove_extra_root_keys = Verquest.configuration.remove_extra_root_keys if remove_extra_root_keys.nil?
24
+ reject_other_version_keys = Verquest.configuration.reject_other_version_keys if reject_other_version_keys.nil?
23
25
 
24
26
  version_class = resolve(version)
25
27
 
26
28
  params = params.dup
27
29
  params = params.to_unsafe_h if params.respond_to?(:to_unsafe_h)
30
+
31
+ if validate && reject_other_version_keys && (other_version_errors = other_version_key_errors(params, version_class)).any?
32
+ return validation_failure(other_version_errors)
33
+ end
34
+
28
35
  params = params.slice(*version_class.all_properties.keys) if remove_extra_root_keys && !version_class.combination?
29
36
  params = version_class.coerce_params(params)
37
+ params = copy_params(params) if validate && version_class.inserts_property_defaults?
30
38
 
31
39
  if validate && (validation_result = version_class.validate_params(params: params)) && validation_result.any?
32
- case Verquest.configuration.validation_error_handling
33
- when :raise
34
- raise InvalidParamsError.new("Validation failed", errors: validation_result)
35
- when :result
36
- Result.failure(validation_result)
37
- end
40
+ validation_failure(validation_result)
38
41
  else
39
42
  begin
40
43
  mapped_params = version_class.map_params(params)
@@ -56,6 +59,37 @@ module Verquest
56
59
  end
57
60
  end
58
61
 
62
+ # Returns the names of the filters the version declares
63
+ #
64
+ # @param version [String, nil] Specific version to use, defaults to configuration setting
65
+ # @return [Array<String>] Filter names in declaration order
66
+ def filter_names(version: nil)
67
+ resolve(version).filters.keys
68
+ end
69
+
70
+ # Filters a target with the version's filters
71
+ #
72
+ # Runs the filter blocks in declaration order. Each block gets the previous block's result and the
73
+ # value of its property in params; a filter whose value is nil or empty is skipped.
74
+ #
75
+ # @example
76
+ # params = DealsQuery.process(request.query_parameters)
77
+ # DealsQuery.apply_filters(Deal.all, params)
78
+ #
79
+ # @param target [Object] What to filter, such as an ActiveRecord relation
80
+ # @param params [Hash{String => Object}] Processed params with String keys, as {#process} returns them (the
81
+ # result's `value` when validation_error_handling is :result); Symbol keys aren't read
82
+ # @param version [String, nil] Specific version to use, defaults to configuration setting
83
+ # @return [Object] The filtered target
84
+ def apply_filters(target, params, version: nil)
85
+ resolve(version).filters.reduce(target) do |filtered, (name, block)|
86
+ value = params[name]
87
+ next filtered if value.nil? || (value.respond_to?(:empty?) && value.empty?)
88
+
89
+ block.call(filtered, value)
90
+ end
91
+ end
92
+
59
93
  # Sets or returns where the request's params come from
60
94
  #
61
95
  # A query request (`location :query`) or path request (`location :path`)
@@ -127,6 +161,8 @@ module Verquest
127
161
 
128
162
  # Validates the generated JSON schema structure
129
163
  #
164
+ # Under `:openapi30` it checks the document from `to_schema`, otherwise the validation schema.
165
+ #
130
166
  # @param version [String, nil] Specific version to use, defaults to configuration setting
131
167
  # @return [Boolean] True if schema is valid
132
168
  def valid_schema?(version: nil)
@@ -137,7 +173,8 @@ module Verquest
137
173
  #
138
174
  # This method validates the schema against the configured JSON Schema metaschema
139
175
  # and returns detailed validation errors if any are found. It's useful for debugging
140
- # schema issues during development and testing.
176
+ # schema issues during development and testing. Under `:openapi30` it checks the document from `to_schema`, so
177
+ # the pointers refer to it.
141
178
  #
142
179
  # @param version [String, nil] Specific version to use, defaults to configuration setting
143
180
  # @return [Array<Hash>] An array of validation error details, empty if schema is valid
@@ -80,8 +80,7 @@ module Verquest
80
80
  #
81
81
  # @return [Hash] The `required` and `dependentRequired` fragment
82
82
  def required_schema
83
- {}.tap do |schema|
84
- schema["required"] = required_properties if required_properties.any?
83
+ required_keyword.tap do |schema|
85
84
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
86
85
  end
87
86
  end
@@ -14,7 +14,10 @@ module Verquest
14
14
  # Initialize a new rule
15
15
  #
16
16
  # @param names [Array<Symbol, String>] The properties the rule names
17
+ # @raise [ArgumentError] If no property is named
17
18
  def initialize(names)
19
+ raise ArgumentError, "Name at least one property" if names.empty?
20
+
18
21
  @property_names = names.map(&:to_s)
19
22
  end
20
23
  end
@@ -65,9 +65,13 @@ module Verquest
65
65
  # @!attribute [rw] query_array_explode
66
66
  # Default explode value of array properties in query requests (`location :query`)
67
67
  # @return [Boolean] true for repeated keys like `status[]=a&status[]=b` (default), false for comma-separated values like `status=a,b`
68
+ #
69
+ # @!attribute [rw] reject_other_version_keys
70
+ # Controls whether `process` reports root keys that only another version of the request declares, when it validates params
71
+ # @return [Boolean] true to report them as validation errors, false to treat them as unknown keys (default)
68
72
  attr_accessor :validate_params, :json_schema_version, :validation_error_handling,
69
73
  :remove_extra_root_keys, :insert_property_defaults, :default_additional_properties,
70
- :query_array_explode
74
+ :query_array_explode, :reject_other_version_keys
71
75
 
72
76
  # @!attribute [r] current_version
73
77
  # A callable object that returns the current API version to use when not explicitly specified
@@ -95,6 +99,7 @@ module Verquest
95
99
  @custom_field_types = {}
96
100
  @default_additional_properties = false
97
101
  @query_array_explode = true
102
+ @reject_other_version_keys = false
98
103
  end
99
104
 
100
105
  # Sets the current version strategy using a callable object
@@ -169,6 +174,15 @@ module Verquest
169
174
  !VERSIONS_WITHOUT_CONST.include?(json_schema_version)
170
175
  end
171
176
 
177
+ # Checks whether documents write nullable as a keyword
178
+ #
179
+ # OpenAPI 3.0 has no "null" type, so its documents use `nullable: true` (see {Verquest::Openapi30}).
180
+ #
181
+ # @return [Boolean] True for OpenAPI 3.0
182
+ def nullable_keyword?
183
+ json_schema_version == :openapi30
184
+ end
185
+
172
186
  # Gets the JSON Schema URI for the configured schema version
173
187
  #
174
188
  # @return [String] The base URI for the configured JSON Schema version
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Verquest
4
- GEM_VERSION = "0.7.1"
4
+ GEM_VERSION = "0.9.0"
5
5
  end
@@ -25,6 +25,15 @@ module Verquest
25
25
  @_required_properties ||= properties.values.select { _1.required == true }.map(&:name)
26
26
  end
27
27
 
28
+ # Returns the `required` keyword for a schema, left out when nothing is required
29
+ #
30
+ # Draft 4 and OpenAPI 3.0 forbid an empty `required` array, and later drafts treat it like no `required`.
31
+ #
32
+ # @return [Hash] `{"required" => names}`, or an empty Hash when no property is required
33
+ def required_keyword
34
+ required_properties.any? ? {"required" => required_properties} : {}
35
+ end
36
+
28
37
  # Returns properties that are conditionally required based on other properties
29
38
  #
30
39
  # This method identifies properties that are required only when certain other
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Verquest
4
+ # Rewrites a JSON Schema into OpenAPI 3.0 forms
5
+ #
6
+ # OpenAPI 3.0 has no "null" type and no type arrays. Properties write the JSON Schema forms, which validators
7
+ # honour, so only documents are converted, when `json_schema_version` is `:openapi30`:
8
+ # - "null" in a type array becomes `nullable: true`
9
+ # - several types become an `anyOf` of single types, each nullable when the schema is
10
+ # - an `anyOf` with a single null alternative becomes `nullable: true`, with an `allOf` around a `$ref`
11
+ # (OpenAPI 3.0 ignores keywords next to `$ref`) or a discriminated `oneOf` (which would reject null),
12
+ # and `null` added to an `enum`
13
+ # - `dependentRequired` becomes the `x-dependentRequired` extension
14
+ #
15
+ # Only schema positions are visited, so a property named "type" is never read as the keyword.
16
+ #
17
+ # @example
18
+ # Verquest::Openapi30.document({"type" => ["string", "null"]})
19
+ # # => {"type" => "string", "nullable" => true}
20
+ module Openapi30
21
+ # The null alternative of a nullable anyOf
22
+ NULL_SCHEMA = {"type" => "null"}.freeze
23
+
24
+ # Keywords whose value is a map from names to schemas
25
+ SCHEMA_MAPS = %w[properties patternProperties dependentSchemas dependencies $defs definitions].freeze
26
+
27
+ # Keywords whose value is a list of schemas
28
+ SCHEMA_LISTS = %w[prefixItems anyOf oneOf allOf].freeze
29
+
30
+ # Keywords whose value is a schema (`items` can also be a list)
31
+ SCHEMAS = %w[
32
+ items additionalProperties not if then else
33
+ contains propertyNames unevaluatedProperties unevaluatedItems additionalItems
34
+ ].freeze
35
+
36
+ # Keywords OpenAPI 3.0 lacks, written as extensions
37
+ RENAMED = {"dependentRequired" => "x-dependentRequired"}.freeze
38
+
39
+ module_function
40
+
41
+ # @param schema [Object] A schema; other values, such as `additionalProperties: false`, are returned as they are
42
+ # @return [Object] A converted copy of the schema
43
+ def document(schema)
44
+ return schema unless schema.is_a?(::Hash)
45
+
46
+ # The null alternative goes first, so a merged alternative's type array meets nullable in type_union
47
+ type_union(nullable_any_of(schema).to_h { |keyword, value| [RENAMED.fetch(keyword, keyword), child(keyword, value)] })
48
+ end
49
+
50
+ # @param keyword [String] The schema keyword
51
+ # @param value [Object] Its value
52
+ # @return [Object] The value, with the schemas it holds converted
53
+ def child(keyword, value)
54
+ if SCHEMA_MAPS.include?(keyword) && value.is_a?(::Hash)
55
+ value.transform_values { |schema| document(schema) }
56
+ elsif (SCHEMA_LISTS.include?(keyword) || SCHEMAS.include?(keyword)) && value.is_a?(::Array)
57
+ value.map { |schema| document(schema) }
58
+ elsif SCHEMAS.include?(keyword)
59
+ document(value)
60
+ else
61
+ value
62
+ end
63
+ end
64
+
65
+ # OpenAPI 3.0 honours nullable only next to type, so each branch of a union carries it, also when a merged
66
+ # nullable alternative has the type array
67
+ #
68
+ # @param schema [Hash] A schema with converted children
69
+ # @return [Hash] The schema without a type array
70
+ def type_union(schema)
71
+ types = schema["type"]
72
+ return schema unless types.is_a?(::Array)
73
+
74
+ others = types - ["null"]
75
+ return schema if others.empty?
76
+
77
+ nullable = (types.include?("null") || schema["nullable"]) ? {"nullable" => true} : {}
78
+ return schema.merge("type" => others.first).merge(nullable) if others.one?
79
+
80
+ any_of(schema.except("type"), others.map { |type| {"type" => type}.merge(nullable) })
81
+ end
82
+
83
+ # @param schema [Hash] A schema without its type
84
+ # @param variants [Array<Hash>] The single-type schemas
85
+ # @return [Hash] The schema with the variants as an anyOf, next to an existing anyOf through allOf
86
+ def any_of(schema, variants)
87
+ return schema.merge("anyOf" => variants) unless schema.key?("anyOf")
88
+
89
+ schema.except("anyOf").merge("allOf" => [*schema["allOf"], {"anyOf" => variants}, {"anyOf" => schema["anyOf"]}])
90
+ end
91
+
92
+ # @param schema [Hash] A schema whose children are not converted yet
93
+ # @return [Hash] The schema without a null alternative in its anyOf
94
+ def nullable_any_of(schema)
95
+ variants = schema["anyOf"]
96
+ return schema unless variants.is_a?(::Array) && variants.include?(NULL_SCHEMA)
97
+
98
+ others = variants - [NULL_SCHEMA]
99
+ return schema if others.empty?
100
+
101
+ siblings = schema.except("anyOf").merge("nullable" => true)
102
+ others.one? ? nullable_alternative(others.first, siblings) : siblings.merge("anyOf" => others)
103
+ end
104
+
105
+ # OpenAPI 3.0 ignores keywords next to $ref, so a nullable $ref goes into an allOf. So does a discriminated
106
+ # oneOf, keeping null outside it as versponse does.
107
+ #
108
+ # @param alternative [Object] The only non-null alternative
109
+ # @param siblings [Hash] The other keywords of the schema, with nullable
110
+ # @return [Hash] The nullable schema
111
+ def nullable_alternative(alternative, siblings)
112
+ return siblings.merge("anyOf" => [alternative]) unless alternative.is_a?(::Hash)
113
+ return {"allOf" => [alternative]}.merge(siblings) if alternative.key?("$ref") || alternative.key?("discriminator")
114
+
115
+ nullable_enum(alternative).merge(siblings)
116
+ end
117
+
118
+ # OpenAPI 3.0 needs null listed in an enum next to nullable
119
+ #
120
+ # @param schema [Hash] The only non-null alternative
121
+ # @return [Hash] The alternative, with nil in its enum
122
+ def nullable_enum(schema)
123
+ schema.key?("enum") ? schema.merge("enum" => schema["enum"] | [nil]) : schema
124
+ end
125
+
126
+ private_class_method :child, :type_union, :any_of, :nullable_any_of, :nullable_alternative, :nullable_enum
127
+ end
128
+ end
@@ -122,7 +122,7 @@ module Verquest
122
122
  "type" => type,
123
123
  "items" => {
124
124
  "type" => "object",
125
- "required" => required_properties,
125
+ **required_keyword,
126
126
  "properties" => all_properties.transform_values { |property| property.to_schema[property.name] },
127
127
  "additionalProperties" => Verquest.configuration.default_additional_properties
128
128
  }.tap do |schema|
@@ -160,7 +160,7 @@ module Verquest
160
160
  "type" => type,
161
161
  "items" => {
162
162
  "type" => "object",
163
- "required" => required_properties,
163
+ **required_keyword,
164
164
  "properties" => all_properties.transform_values { |property| property.to_validation_schema(version: version)[property.name] },
165
165
  "additionalProperties" => Verquest.configuration.default_additional_properties
166
166
  }.tap do |schema|
@@ -4,9 +4,27 @@ module Verquest
4
4
  module Properties
5
5
  # The Enum class represents a enum property with a list of possible values in a JSON schema.
6
6
  #
7
+ # The type is inferred from the values unless `type:` is given, and every value must fit it.
8
+ #
7
9
  # @example
8
10
  # enum = Enum.new(name: "type", values: ["member", "admin"])
11
+ # enum.to_schema # => {"type" => {"type" => "string", "enum" => ["member", "admin"]}}
9
12
  class Enum < Base
13
+ # Ruby classes the values of each JSON type can have
14
+ VALUE_CLASSES = {
15
+ "string" => [::String],
16
+ "integer" => [::Integer],
17
+ "number" => [::Numeric],
18
+ "boolean" => [::TrueClass, ::FalseClass],
19
+ "object" => [::Hash]
20
+ }.freeze
21
+
22
+ # Classes of the JSON values that need no further check inside a Hash
23
+ JSON_SCALARS = [::String, ::TrueClass, ::FalseClass, ::NilClass].freeze
24
+
25
+ # Added to errors about Symbols
26
+ SYMBOL_HINT = " (Symbols never match JSON values, use Strings)"
27
+
10
28
  # Initialize a new Enum property
11
29
  #
12
30
  # @param name [String, Symbol] The name of the property
@@ -14,31 +32,35 @@ module Verquest
14
32
  # @param required [Boolean, Array<Symbol>] Whether this property is required, or array of dependency names
15
33
  # @param nullable [Boolean] Whether this property can be null
16
34
  # @param map [String, nil] The mapping path for this property
35
+ # @param type [String, Symbol, Array<String, Symbol>, nil] The JSON type of the values, inferred from them when nil
17
36
  # @param schema_options [Hash] Additional JSON schema options for this property
18
37
  # @raise [ArgumentError] If attempting to map an enum to root without a name
19
- # @raise [ArgumentError] If values is empty
20
- # @raise [ArgumentError] If values are not unique
38
+ # @raise [ArgumentError] If values is not an Array, or is empty
39
+ # @raise [ArgumentError] If values are not unique, comparing them as JSON (1 and 1.0 are the same)
21
40
  # @raise [ArgumentError] If only one value is provided (should use const instead)
22
- def initialize(name:, values:, required: false, nullable: false, map: nil, **schema_options)
41
+ # @raise [ArgumentError] If values include nil without nullable, or a number that isn't finite
42
+ # @raise [ArgumentError] If a value has no JSON type, the type is unknown, or a value isn't of the type
43
+ # @raise [ArgumentError] If a Hash value has a key that isn't a String, or contains a value that isn't JSON
44
+ def initialize(name:, values:, required: false, nullable: false, map: nil, type: nil, **schema_options)
23
45
  raise ArgumentError, "You can not map enums to the root without a name" if map == "/"
24
- raise ArgumentError, "Values must not be empty" if values.empty?
25
- raise ArgumentError, "Values must be unique" if values.uniq.length != values.length
26
- raise ArgumentError, "Use const for a single value" if values.length == 1
46
+
47
+ check_values!(values, nullable)
27
48
 
28
49
  @name = name.to_s
29
50
  @values = nullable ? values | [nil] : values
51
+ @types = type.nil? ? inferred_types : checked_types(type)
30
52
  @required = required
31
53
  @nullable = nullable
32
54
  @map = map
33
- @schema_options = schema_options&.transform_keys(&:to_s)
55
+ @schema_options = schema_options.transform_keys(&:to_s).except("type")
34
56
  end
35
57
 
36
- # Generate JSON schema definition for this enum
58
+ # Generate JSON schema definition for this enum. Nullable adds "null" to the type.
37
59
  #
38
60
  # @return [Hash] The schema definition for this enum
39
61
  def to_schema
40
62
  {
41
- name => {"enum" => values}.merge(schema_options)
63
+ name => {"type" => schema_type, "enum" => values}.merge(schema_options)
42
64
  }
43
65
  end
44
66
 
@@ -55,7 +77,118 @@ module Verquest
55
77
 
56
78
  private
57
79
 
58
- attr_reader :values, :schema_options
80
+ attr_reader :values, :types, :schema_options
81
+
82
+ # @param values [Array] The given values
83
+ # @param nullable [Boolean] Whether the enum can be null
84
+ # @raise [ArgumentError] If the values are not an Array, empty, not JSON, not unique, a single value, or include nil
85
+ # without nullable
86
+ def check_values!(values, nullable)
87
+ raise ArgumentError, "Values must be an Array" unless values.is_a?(::Array)
88
+ raise ArgumentError, "Values must not be empty" if values.empty?
89
+
90
+ values.each { |value| check_json!(value, value) }
91
+ raise ArgumentError, "Values must be unique" if values.uniq { |value| json_value(value) }.length != values.length
92
+ raise ArgumentError, "Use const for a single value" if values.length == 1
93
+ raise ArgumentError, "Values include nil, which needs nullable: true" if values.include?(nil) && !nullable
94
+ end
95
+
96
+ # Checks numbers and walks Hashes; top-level Arrays and other classes are left to the type check
97
+ #
98
+ # @param value [Object] An enum value, or a part of a Hash value
99
+ # @param enum_value [Object] The enum value, for errors
100
+ # @param nested [Boolean] Whether the value is inside a Hash
101
+ # @raise [ArgumentError] If a number isn't finite, or a Hash value has a key or part that isn't JSON
102
+ def check_json!(value, enum_value, nested: false)
103
+ case value
104
+ when ::Numeric then raise ArgumentError, "Enum values must be finite numbers" unless finite?(value)
105
+ when ::Hash then value.each { |key, item| check_key!(key, enum_value) || check_json!(item, enum_value, nested: true) }
106
+ when ::Array then value.each { |item| check_json!(item, enum_value, nested: true) } if nested
107
+ when *JSON_SCALARS then nil
108
+ else
109
+ raise ArgumentError, "Enum value #{enum_value.inspect} contains #{value.inspect}, which is not a JSON value#{symbol_hint(value)}" if nested
110
+ end
111
+ end
112
+
113
+ # @param key [Object] A key of a Hash value
114
+ # @param enum_value [Object] The enum value, for errors
115
+ # @return [nil]
116
+ # @raise [ArgumentError] If the key isn't a String
117
+ def check_key!(key, enum_value)
118
+ return if key.is_a?(::String)
119
+
120
+ raise ArgumentError, "Enum value #{enum_value.inspect} has key #{key.inspect}, which is not a String#{symbol_hint(key)}"
121
+ end
122
+
123
+ # @param value [Numeric] A number
124
+ # @return [Boolean] Whether JSON can represent the number
125
+ def finite?(value)
126
+ value.real? && value.finite?
127
+ end
128
+
129
+ # @param value [Object] The value an error is about
130
+ # @return [String, nil] The hint for a Symbol
131
+ def symbol_hint(value)
132
+ SYMBOL_HINT if value.is_a?(::Symbol)
133
+ end
134
+
135
+ # @return [String, Array<String>] The type, with "null" when nullable
136
+ def schema_type
137
+ all = nullable ? types | ["null"] : types
138
+ (all.size == 1) ? all.first : all
139
+ end
140
+
141
+ # @return [Array<String>] The types of the non-nil values; integers next to other numerics are numbers
142
+ def inferred_types
143
+ found = values.compact.map { |value| json_type(value) }.uniq
144
+ found.delete("integer") if found.include?("number")
145
+ found
146
+ end
147
+
148
+ # VALUE_CLASSES lists "integer" before "number", so an Integer is an integer
149
+ #
150
+ # @param value [Object] A non-nil enum value
151
+ # @return [String] The JSON type of the value
152
+ # @raise [ArgumentError] If the value has no JSON type
153
+ def json_type(value)
154
+ type = VALUE_CLASSES.keys.find { |name| of_type?(value, name) }
155
+ return type if type
156
+
157
+ raise ArgumentError, "Enum value #{value.inspect} is not a String, Numeric, boolean or Hash#{symbol_hint(value)}"
158
+ end
159
+
160
+ # @param type [String, Symbol, Array<String, Symbol>] The given type
161
+ # @return [Array<String>] The given types as strings
162
+ # @raise [ArgumentError] If a type is unknown or a value isn't of the types
163
+ def checked_types(type)
164
+ given = Array(type).map(&:to_s).uniq
165
+ if given.empty? || !given.all? { |name| VALUE_CLASSES.key?(name) }
166
+ raise ArgumentError, "Unknown enum type #{type.inspect}, use one of #{VALUE_CLASSES.keys.join(", ")}"
167
+ end
168
+
169
+ invalid = values.compact.reject { |value| given.any? { |name| of_type?(value, name) } }
170
+ raise ArgumentError, "Enum value #{invalid.first.inspect} is not of type #{given.join(" or ")}" unless invalid.empty?
171
+
172
+ given
173
+ end
174
+
175
+ # @param value [Object] A non-nil enum value
176
+ # @param name [String] A JSON type in VALUE_CLASSES
177
+ # @return [Boolean] Whether the value is of the type
178
+ def of_type?(value, name)
179
+ VALUE_CLASSES.fetch(name).any? { |klass| value.is_a?(klass) }
180
+ end
181
+
182
+ # @param value [Object] An enum value, or a part of a Hash value
183
+ # @return [Object] The value as JSON compares it: whole numbers as Integers, also inside Hashes and Arrays
184
+ def json_value(value)
185
+ case value
186
+ when ::Hash then value.transform_values { |item| json_value(item) }
187
+ when ::Array then value.map { |item| json_value(item) }
188
+ when ::Numeric then (finite?(value) && value == value.to_i) ? value.to_i : value
189
+ else value
190
+ end
191
+ end
59
192
  end
60
193
  end
61
194
  end
@@ -59,7 +59,7 @@ module Verquest
59
59
  {
60
60
  name => {
61
61
  "type" => type,
62
- "required" => required_properties,
62
+ **required_keyword,
63
63
  "properties" => all_properties.transform_values { |property| property.to_schema[property.name] }
64
64
  }.merge(schema_options).tap do |schema|
65
65
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
@@ -76,7 +76,7 @@ module Verquest
76
76
  {
77
77
  name => {
78
78
  "type" => type,
79
- "required" => required_properties,
79
+ **required_keyword,
80
80
  "properties" => all_properties.transform_values { |property| property.to_validation_schema(version: version)[property.name] }
81
81
  }.merge(schema_options).tap do |schema|
82
82
  schema["dependentRequired"] = dependent_required_properties if dependent_required_properties.any?
@@ -106,7 +106,7 @@ module Verquest
106
106
  when "number" then coerce_number(value)
107
107
  when "boolean" then coerce_boolean(value)
108
108
  when "null" then (value.nil? || value == "") ? nil : NO_MATCH
109
- when "string" then value.is_a?(::String) ? value : NO_MATCH
109
+ when "string" then coerce_string(value, value_schema)
110
110
  when "array" then coerce_array(value, value_schema, path)
111
111
  when "object" then value.is_a?(::Hash) ? coerce_properties(value, value_schema, path) : NO_MATCH
112
112
  else NO_MATCH
@@ -136,6 +136,16 @@ module Verquest
136
136
  BOOLEANS.fetch(value, NO_MATCH)
137
137
  end
138
138
 
139
+ # A string outside the schema's enum tries the next type, so "" can still map to nil
140
+ #
141
+ # @return [String, Object] The string or NO_MATCH
142
+ def coerce_string(value, value_schema)
143
+ return NO_MATCH unless value.is_a?(::String)
144
+ return NO_MATCH if value_schema.key?("enum") && !value_schema["enum"].include?(value)
145
+
146
+ value
147
+ end
148
+
139
149
  # Splits a string by the array's explode value and converts each item;
140
150
  # an item no rule converts is kept as it is
141
151
  def coerce_array(value, array_schema, path)
@@ -9,7 +9,7 @@ module Verquest
9
9
  # (`param[:in]`, `param[:style]`, `param[:schema][:type]`).
10
10
  #
11
11
  # @example
12
- # schema = {"type" => "object", "required" => [], "properties" => {"page" => {"type" => "integer"}}}
12
+ # schema = {"type" => "object", "properties" => {"page" => {"type" => "integer"}}}
13
13
  # Verquest::Query::Parameters.new(schema:, options: {}).call
14
14
  # # => [{name: "page", in: :query, required: false, schema: {type: "integer"}}]
15
15
  class Parameters