verquest 0.8.0 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4445e1ed3a032827a00b4805bb1eb3bcb57eb11cf3a261e334d4bb5362df953d
4
- data.tar.gz: 14a3b0eb7fc630f6d227f4efc439eabfde307ed0e8d3c133a68b96120e6b588e
3
+ metadata.gz: fd6f2a0f230e6345a0e63458644937161ee4c2fe631d3d8112c1a9ba559220fc
4
+ data.tar.gz: 64c65c15ee3bb1a7b1bd4f5c93778bae79a154ae86502dc143298db85db6c4ce
5
5
  SHA512:
6
- metadata.gz: 6605a7c2d01d8a1d89388340592f5f9ac7e61220f705ce06eecdc50b39b0b01771c70afa0311f4ca4ebd21f72c0ca61732ca2ab27e9fc332d5761f357f909e4a
7
- data.tar.gz: c8dacd48fec778f398971dcf1f797fb639edd771069070c64c2f5ee3a9eb3c1389483f5dbb6348eb4607c579624ba3fb74a94fe64c05f9a7bd7cbe79112d9fd8
6
+ metadata.gz: d5e340359033758d79e228543e7b070a4aff9ef0d4026b695ec8c418527e8a476582b674deb8a74892ff328541e5a34ea0667e32b83d5dbb0f4c64ba182663c4
7
+ data.tar.gz: dec4b9a1337c8d8656fbc6b1cb799155d208c20f86fa0a4b4ec605ef10ed32b90b247818137ee4b60d54ba5fa0e1b570be7aad0fe1d13db45eabc798ba73d130
data/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.9.0] - 2026-11-09
4
+
5
+ ### Added
6
+ - `filter` declares a property with `field`, `array` or `enum` (`as:`) and the block that filters by its value; `apply_filters(target, params, version:)` runs a version's filters in declaration order, skipping nil and empty values, and `filter_names(version:)` lists them. Filters are inherited, excluded and replaced with their properties. A filter with `map:`, another `as:`, no block, or outside a version's root raises `Verquest::DefinitionError`.
7
+ - `process(..., reject_other_version_keys: true)` (or `config.reject_other_version_keys`) reports root keys that only another version declares as validation errors of type `other_version`, when params are validated.
8
+
9
+ ### Changed
10
+ - Validation skips json_schemer's default insertion when the schema declares no `default`, which makes `process` about 15% faster for such schemas.
11
+
12
+ ### Fixed
13
+ - `process` no longer inserts defaults into the caller's nested hashes, and no longer raises `FrozenError` for frozen nested params when it inserts defaults.
14
+
3
15
  ## [0.8.0] - 2026-11-06
4
16
 
5
17
  ### Changed
data/README.md CHANGED
@@ -20,7 +20,7 @@ Sponsored by [Stora](https://stora.co)
20
20
 
21
21
  - [Installation](#installation)
22
22
  - [Quick Start](#quick-start)
23
- - [Core Features](#core-features): [schema definition](#schema-definition-and-validation), [oneOf](#oneof), [conditional schemas](#conditional-schemas), [custom field types](#custom-field-types), [versioning](#versioning), [mapping](#mapping-request-structure), [query parameters](#query-parameters), [path parameters](#path-parameters), [OpenAPI components](#component-generation-for-openapi)
23
+ - [Core Features](#core-features): [schema definition](#schema-definition-and-validation), [oneOf](#oneof), [conditional schemas](#conditional-schemas), [custom field types](#custom-field-types), [versioning](#versioning), [mapping](#mapping-request-structure), [query parameters](#query-parameters), [filters](#filters), [path parameters](#path-parameters), [OpenAPI components](#component-generation-for-openapi)
24
24
  - [Rails and rswag](docs/rails.md)
25
25
  - [Configuration](#configuration)
26
26
 
@@ -29,7 +29,7 @@ Sponsored by [Stora](https://stora.co)
29
29
  Add this line to your application's Gemfile:
30
30
 
31
31
  ```ruby
32
- gem "verquest", "~> 0.7"
32
+ gem "verquest", "~> 0.9"
33
33
  ```
34
34
 
35
35
  And then execute:
@@ -134,7 +134,8 @@ error.errors
134
134
  Set `config.current_version` to drop the `version:` argument, or `config.validation_error_handling = :result` to get a `Verquest::Result` instead of an exception (see [Configuration](#configuration)). For query and path parameters in controllers, see [Rails and rswag](docs/rails.md).
135
135
 
136
136
  ### JSON schema for OpenAPI
137
- You can generate JSON Schema for your versioned requests, which can be used for API documentation:
137
+
138
+ `to_schema` returns the JSON Schema of a version for your API documentation. References stay `$ref`s:
138
139
 
139
140
  ```ruby
140
141
  UserCreateRequest.to_schema(version: "2025-06")
@@ -161,7 +162,8 @@ Output:
161
162
  "name" => {"type" => "string", "description" => "Name of the permission"},
162
163
  "read" => {"type" => "boolean", "description" => "Permission to read"},
163
164
  "write" => {"type" => "boolean", "description" => "Permission to write"}
164
- }
165
+ },
166
+ "additionalProperties" => false
165
167
  },
166
168
  "description" => "Permissions associated with the user"
167
169
  },
@@ -182,9 +184,11 @@ Output:
182
184
  "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
183
185
  "mastodon" => {"type" => "string", "format" => "uri", "description" => "Mastodon profile URL"}
184
186
  },
187
+ "additionalProperties" => false,
185
188
  "description" => "Some social networks"
186
189
  }
187
- }
190
+ },
191
+ "additionalProperties" => false
188
192
  },
189
193
  "company" => {"const" => "Awesome Inc."}
190
194
  },
@@ -194,7 +198,7 @@ Output:
194
198
 
195
199
  ### JSON schema for validation
196
200
 
197
- You can check the validation JSON schema for a specific version of your request:
201
+ `to_validation_schema` returns the schema that `process` validates against, with references inlined:
198
202
 
199
203
  ```ruby
200
204
  UserCreateRequest.to_validation_schema(version: "2025-06")
@@ -210,7 +214,7 @@ Output:
210
214
  "first_name" => {"type" => "string", "description" => "The first name of the user", "maxLength" => 50},
211
215
  "last_name" => {"type" => "string", "description" => "The last name of the user", "maxLength" => 50},
212
216
  "email" => {"type" => "string", "format" => "email", "description" => "The email address of the user"},
213
- "birth_date" => {"type" => "string", "format" => "date", "description" => "The birth date of the user"},
217
+ "birth_date" => {"type" => ["string", "null"], "format" => "date", "description" => "The birth date of the user"},
214
218
  "address" => { # from the AddressCreateRequest
215
219
  "type" => "object",
216
220
  "description" => "Address Create Request",
@@ -231,7 +235,8 @@ Output:
231
235
  "name" => {"type" => "string", "description" => "Name of the permission"},
232
236
  "read" => {"type" => "boolean", "description" => "Permission to read"},
233
237
  "write" => {"type" => "boolean", "description" => "Permission to write"}
234
- }
238
+ },
239
+ "additionalProperties" => false
235
240
  },
236
241
  "description" => "Permissions associated with the user"
237
242
  },
@@ -241,26 +246,30 @@ Output:
241
246
  "default" => "member",
242
247
  "description" => "Role of the user"
243
248
  },
244
- "profile_details" => {"type" => "object",
249
+ "profile_details" => {
250
+ "type" => "object",
245
251
  "properties" => {
246
252
  "bio" => {"type" => "string", "description" => "Short biography of the user"},
247
253
  "hobbies" => {"type" => "array", "items" => {"type" => "string"}, "description" => "Tags associated with the user"},
248
254
  "social_links" => {
249
- "type" => "object",
255
+ "type" => "object",
250
256
  "properties" => {
251
- "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
257
+ "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
252
258
  "mastodon" => {"type" => "string", "format" => "uri", "description" => "Mastodon profile URL"}
253
- },
254
- "description" => "Some social networks"}
259
+ },
260
+ "additionalProperties" => false,
261
+ "description" => "Some social networks"
262
+ }
255
263
  },
256
- "company" => {"const" => "Awesome Inc."}
257
- }
264
+ "additionalProperties" => false
265
+ },
266
+ "company" => {"const" => "Awesome Inc."}
258
267
  },
259
268
  "additionalProperties" => false
260
269
  }
261
270
  ```
262
271
 
263
- You can also validate it to ensure it meets the JSON Schema standards. Under `:openapi30` this checks the document from `to_schema` against the OpenAPI 3.0 meta-schema, since validation schemas keep JSON Schema forms OpenAPI 3.0 forbids:
272
+ `valid_schema?` and `validate_schema` check the validation schema against the meta-schema of `config.json_schema_version`. Under `:openapi30`, they check the `to_schema` document instead, because validation schemas keep JSON Schema forms that OpenAPI 3.0 forbids:
264
273
 
265
274
  ```ruby
266
275
  UserCreateRequest.valid_schema?(version: "2025-06") # => true/false
@@ -615,7 +624,6 @@ end
615
624
  {
616
625
  "type" => "object",
617
626
  "description" => "User Create Request",
618
- "required" => ["email"],
619
627
  "properties" => {
620
628
  "email" => {
621
629
  "type" => "string",
@@ -678,9 +686,8 @@ class UserCreateRequest < Verquest::Base
678
686
  end
679
687
  ```
680
688
 
681
- Internal `Verquest::VersionResolver` is then used to resolve the right version for the one specified in the call. It implements a "downgrading" strategy - when an exact version match isn't found, it returns the closest earlier version.
689
+ `Verquest::VersionResolver` picks the version block for the requested version. When no block matches exactly, it picks the closest earlier one:
682
690
 
683
- Example:
684
691
  ```ruby
685
692
  UserCreateRequest.process(params, version: "2025-05") # => use the defined version "2025-04"
686
693
  UserCreateRequest.process(params, version: "2025-06") # => use the defined version "2025-06"
@@ -689,9 +696,9 @@ UserCreateRequest.process(params, version: "2025-08") # => use the defined versi
689
696
  UserCreateRequest.process(params, version: "2025-10") # => use the closest earlier version "2025-08"
690
697
  ```
691
698
 
692
- This is used across all referenced requests, so if you have a `UserRequest` that references an `AddressCreateRequest`, it will also resolve the correct version of the `AddressCreateRequest` based on the initial requested version (as the `AddressCreateRequest` can have different versions defined).
699
+ References resolve the same way. When `UserCreateRequest` references `AddressCreateRequest`, the requested version also picks the `AddressCreateRequest` block, so the two classes can declare different versions.
693
700
 
694
- The goal here is to avoid redefining the same request structure in multiple versions when there are no changes, and to facilitate the easy evolution of API requests over time. When a new API version is created and there are no changes to the requests, you don't need to update anything.
701
+ A new API version that doesn't change a request needs no new `version` block in it.
695
702
 
696
703
  #### Supported versions
697
704
 
@@ -721,13 +728,11 @@ OverlockRequest.process(params, version: "2026-06") # => raises Verquest::Versio
721
728
 
722
729
  ### Mapping request structure
723
730
 
724
- Verquest's mapping system allows transforming external API request structures into your internal application data structures.
725
-
726
- Here’s a short example: we store the address in the same table as the user internally, but the API request structure is different.
731
+ `map:` turns the public request structure into the structure your app uses. In this example, the app stores the address in the users table, so the address fields move to the root:
727
732
 
728
733
  ```ruby
729
734
  class UserCreateRequest < Verquest::Base
730
- version "2025-06", exclude_properties: %i[street city] do
735
+ version "2025-06" do
731
736
  field :full_name, type: :string, map: "name"
732
737
  field :email, type: :string, format: "email", required: true
733
738
  field :phone, type: :string
@@ -741,40 +746,43 @@ class UserCreateRequest < Verquest::Base
741
746
  end
742
747
  ```
743
748
 
744
- When called with `UserCreateRequest.process(params)`, the `address` object will be mapped to the internal structure with keys `address_street`, `address_city`, and `address_zip`.
749
+ `UserCreateRequest.process` turns these params:
745
750
 
746
- Example request params
747
751
  ```ruby
748
752
  {
749
- "full_name": "John Doe",
750
- "email": "john@doe.com",
751
- "phone": "1234567890",
752
- "address": {
753
- "street": "123 Main St",
754
- "city": "Springfield",
755
- "postal_code": "12345"
753
+ "full_name" => "John Doe",
754
+ "email" => "john@doe.com",
755
+ "phone" => "1234567890",
756
+ "address" => {
757
+ "street" => "123 Main St",
758
+ "city" => "Springfield",
759
+ "postal_code" => "12345"
756
760
  }
757
761
  }
758
762
  ```
759
763
 
760
- Will be transformed to:
764
+ into:
765
+
761
766
  ```ruby
762
767
  {
763
- "name": "John Doe",
764
- "email": "john@doe.com",
765
- "phone": "1234567890",
766
- "address_street": "123 Main St",
767
- "address_city": "Springfield",
768
- "address_zip": "12345"
768
+ "name" => "John Doe",
769
+ "email" => "john@doe.com",
770
+ "phone" => "1234567890",
771
+ "address_street" => "123 Main St",
772
+ "address_city" => "Springfield",
773
+ "address_zip" => "12345"
769
774
  }
770
775
  ```
771
776
 
772
- What you can use:
773
- - `/` to reference the root of the request structure
774
- - `nested/structure` use slash notation to reference nested structures
775
- - if the `map` is not set, the field name will be used as the key in the internal structure
777
+ `map:` takes one of these forms:
778
+
779
+ - `"name"`: a key at the same level;
780
+ - `"/name"`: a key at the root;
781
+ - `"nested/structure"`: a key inside nested objects.
782
+
783
+ Without `map:`, the property name is the key.
776
784
 
777
- To get the mapping to map the request structure back to the external API structure, you can use the `external_mapping` method:
785
+ `external_mapping` returns the mapping back, from internal keys to external paths:
778
786
 
779
787
  ```ruby
780
788
  UserCreateRequest.external_mapping(version: "2025-06")
@@ -807,12 +815,20 @@ class DealsIndexQuery < Verquest::Base
807
815
  field :page, type: :integer, minimum: 1, default: 1
808
816
  field :archived, type: :boolean
809
817
  enum :sort_direction, values: %w[ASC DESC], default: "DESC"
810
- array :status, type: :string, explode: false, item_schema_options: {enum: %w[open won lost]}
818
+ filter :status, as: :array, type: :string, explode: false, item_schema_options: {enum: %w[open won lost]} do |deals, value|
819
+ deals.where(status: value)
820
+ end
811
821
 
812
822
  object :created do # sent as created[after]=...
813
823
  field :after, type: :string, format: "date-time", map: "/created_after"
814
824
  end
815
825
  end
826
+
827
+ version "2025-08" do # inherits the 2025-06 properties and filters
828
+ filter :site_id, type: :string do |deals, value|
829
+ deals.where(site_id: value)
830
+ end
831
+ end
816
832
  end
817
833
 
818
834
  DealsIndexQuery.process(request.query_parameters, version: "2025-06")
@@ -820,6 +836,8 @@ DealsIndexQuery.process(request.query_parameters, version: "2025-06")
820
836
  # => {"page" => 2, "archived" => true, "sort_direction" => "DESC", "status" => ["open", "won"], "created_after" => "2025-01-01T00:00:00Z"}
821
837
  ```
822
838
 
839
+ `filter :status, as: :array` declares the same property as `array :status`, plus a block that [Filters](#filters) describes.
840
+
823
841
  Conversion follows the validation schema:
824
842
  - `integer` and `number` from digits (`"2"`, `"-1.5"`), `boolean` from `"true"` and `"false"`, `null` from an empty string when the schema allows it (a string outside an enum's values tries the next type, so `""` is `nil` in a nullable string enum);
825
843
  - arrays split on commas with `explode: false` (`status=open,won`), or come from repeated keys with `explode: true` (`status[]=open&status[]=won`; Rails keeps only the last value of a plain repeated key). `config.query_array_explode` sets the default (`true`);
@@ -845,6 +863,36 @@ array :status, type: :string, explode: false, item_schema_options: {enum: %w[ope
845
863
 
846
864
  A property reference to another query class reuses its definition, e.g. a shared `expand` parameter: `reference :expand, from: ExpandQuery, property: :expand`.
847
865
 
866
+ ### Filters
867
+
868
+ `filter` declares a property and the block that filters by its value. The property is a `field` by default, an `array` with `as: :array`, or an `enum` with `as: :enum`, in a body or a query request. `apply_filters` passes the target through the version's filters in declaration order, and skips a filter when its value is nil or empty. `DealsIndexQuery` from [Query parameters](#query-parameters) filters by `status` from `2025-06`, and also by `site_id` from `2025-08`:
869
+
870
+ ```ruby
871
+ params = DealsIndexQuery.process(request.query_parameters, version: "2025-08")
872
+ DealsIndexQuery.apply_filters(Deal.all, params, version: "2025-08")
873
+ DealsIndexQuery.filter_names(version: "2025-08") # => ["status", "site_id"]
874
+ ```
875
+
876
+ - Filters follow the rules of properties. A later version inherits them, `exclude_properties` removes one, and redeclaring a filter replaces its block. Redeclaring it as a plain property, such as `field :status`, stops it filtering.
877
+ - `reference` copies the property without its filter.
878
+ - The block runs only from `apply_filters`, with `self` set to the request class.
879
+ - `apply_filters` reads the params by their String names, as `process` returns them. With `validation_error_handling = :result`, pass the result's `value`.
880
+ - A filter must be at the root of a version, and it can't use `map:`. Otherwise defining the version raises `Verquest::DefinitionError`.
881
+
882
+ [`test/support/examples/deals_index_query.rb`](test/support/examples/deals_index_query.rb) runs the same query against an Array of Hashes.
883
+
884
+ #### Reject keys from other versions
885
+
886
+ `process` drops root keys that the version doesn't declare. A client that sends `site_id` to `2025-06` gets an unfiltered list and no error. With `reject_other_version_keys: true`, `process` reports a root key that only another version declares as a validation error:
887
+
888
+ ```ruby
889
+ DealsIndexQuery.process({"site_id" => "site_1"}, version: "2025-06", reject_other_version_keys: true)
890
+ # raises Verquest::InvalidParamsError with
891
+ # [{pointer: "/site_id", type: "other_version", message: "`site_id` isn't available in version 2025-06", details: nil}]
892
+ ```
893
+
894
+ `remove_extra_root_keys` still drops keys that no version declares, such as `utm_source`. The check works for body requests too, and runs only when `process` validates the params. `config.reject_other_version_keys` sets the default (`false`).
895
+
848
896
  ### Path parameters
849
897
 
850
898
  `location :path` works like `location :query`, but documents `in: :path` parameters. Path parameters must be required scalars; arrays, objects, one_of and optional properties raise `Verquest::DefinitionError`.
@@ -899,6 +947,9 @@ Verquest.configure do |config|
899
947
 
900
948
  # Remove extra root keys from provided params
901
949
  config.remove_extra_root_keys = true # default
950
+
951
+ # Report root keys that only another version declares, see Filters
952
+ config.reject_other_version_keys = false # default
902
953
 
903
954
  # Set custom version resolver
904
955
  config.version_resolver = CustomVersionResolver # default is `Verquest::VersionResolver`
data/Rakefile CHANGED
@@ -32,9 +32,10 @@ task :yard do
32
32
  puts "\nYARD documentation: 100% documented"
33
33
  end
34
34
 
35
- desc "Benchmark the transformer (objects allocated and calls per second)"
35
+ desc "Benchmark the transformer and process (objects allocated and calls per second)"
36
36
  task :bench do
37
37
  ruby "-Ilib", "bench/transformer.rb"
38
+ ruby "-Ilib", "bench/process.rb"
38
39
  end
39
40
 
40
41
  task default: %i[test rubocop yard]
data/docs/rails.md CHANGED
@@ -62,7 +62,8 @@ module VerquestParams
62
62
 
63
63
  # Every path class applies, so /deals/:deal_id/notes/:id can check both IDs
64
64
  @path_params = by_location.fetch(:path, []).to_h { |declaration| process_path_param(declaration) }
65
- # Unknown query keys (cache busters, tracking) are dropped instead of rejected
65
+ # Unknown query keys (cache busters, tracking) are dropped instead of rejected. Add
66
+ # `reject_other_version_keys: true` to reject keys from another version, such as a newer filter.
66
67
  @query_params = by_location[:query]&.first&.dig(:class)&.process(request.query_parameters, remove_extra_root_keys: true)
67
68
  @body_params = by_location[:body]&.first&.dig(:class)&.process(request.request_parameters)
68
69
  end
@@ -115,6 +116,10 @@ class DealsController < ApplicationController
115
116
  verquest_params DealsIndexQuery, only: :index
116
117
  verquest_params DealUpdateRequest, only: :update
117
118
 
119
+ def index
120
+ render json: DealsIndexQuery.apply_filters(Deal.all, query_params)
121
+ end
122
+
118
123
  def show
119
124
  render json: Deal.find_by!(public_id: path_params["id"])
120
125
  end
@@ -127,6 +132,8 @@ end
127
132
 
128
133
  `GET /deals/con_123` then returns 422 with `{"pointer" => "/id", ...}`, and `POST /deals/con_123/win` with `{"pointer" => "/deal_id", ...}`.
129
134
 
135
+ `DealsIndexQuery` declares its filters with `filter` (see [Filters](../README.md#filters)). `apply_filters` takes the version from `config.current_version`, like `process`. `GET /2025-06/deals?site_id=site_1` lists every deal, because `site_id` is a `2025-08` filter and `process` drops it. With `reject_other_version_keys: true`, the same request returns 422 with `{"pointer" => "/site_id", "type" => "other_version", ...}`.
136
+
130
137
  ## rswag
131
138
 
132
139
  A shared context documents a query or path class with `to_parameters`. `name:` renames a path class's parameter to the route key, and `description:` replaces its description:
@@ -8,6 +8,9 @@ module Verquest
8
8
  #
9
9
  # @api private
10
10
  module Base::PrivateClassMethods
11
+ # Property methods a filter can declare its property with
12
+ FILTER_PROPERTY_METHODS = %i[field array enum].freeze
13
+
11
14
  # Resolves the version to use, either from the provided version,
12
15
  # configuration's current_version, or raises an error if none is available
13
16
  #
@@ -87,6 +90,18 @@ module Verquest
87
90
  raise VersionNotFoundError, "Version '#{version}' is outside supported_versions (#{range}) of #{name || inspect}"
88
91
  end
89
92
 
93
+ # Copies the hashes and arrays in params, so inserting defaults leaves the caller's params alone
94
+ #
95
+ # @param value [Object] The params or a value inside them
96
+ # @return [Object] A copy of hashes and arrays, other values as they are
97
+ def copy_params(value)
98
+ case value
99
+ when Hash then value.transform_values { |item| copy_params(item) }
100
+ when Array then value.map { |item| copy_params(item) }
101
+ else value
102
+ end
103
+ end
104
+
90
105
  # Defines a new version with optional inheritance from another version
91
106
  #
92
107
  # @param name [String] The name/identifier of the version
@@ -106,6 +121,7 @@ module Verquest
106
121
 
107
122
  @default_options = {}
108
123
  @current_scope = version
124
+ @defining_version = version
109
125
 
110
126
  instance_exec(&block)
111
127
  ensure
@@ -336,6 +352,37 @@ module Verquest
336
352
  add_property(array, parameter_examples)
337
353
  end
338
354
 
355
+ # Defines a property and the block that filters by its processed value
356
+ #
357
+ # The property is declared with `field`, `array` or `enum` (`as:`), with the other options. The
358
+ # block is stored, not run: {PublicClassMethods#apply_filters} calls it later, and `self` inside it
359
+ # is the request class, so the class's private class methods are available. Filters are inherited,
360
+ # excluded and replaced with their properties.
361
+ #
362
+ # @example
363
+ # filter :status, as: :array, type: :string, explode: false do |target, value|
364
+ # target.where(status: value)
365
+ # end
366
+ #
367
+ # @param name [Symbol] The name of the property
368
+ # @param as [Symbol] `:field` (default), `:array` or `:enum`
369
+ # @param options [Hash] Options for the property method
370
+ # @yieldparam target [Object] What is being filtered, as returned by the previous filter
371
+ # @yieldparam value [Object] The property's processed value, never nil or empty
372
+ # @yieldreturn [Object] The filtered target
373
+ # @return [void]
374
+ # @raise [Verquest::DefinitionError] Without a block, with another `as:`, with `map:`, or outside a version's root
375
+ def filter(name, as: :field, **options, &block)
376
+ label = "Filter '#{name}' in version '#{@defining_version&.name}'"
377
+ raise DefinitionError, "#{label} needs a block that filters the target" unless block
378
+ raise DefinitionError, "#{label} can't be declared as: #{as.inspect}, only as :field, :array or :enum" unless FILTER_PROPERTY_METHODS.include?(as)
379
+ raise DefinitionError, "#{label} can't use map:, apply_filters reads the value by its name" if options.key?(:map)
380
+ raise DefinitionError, "#{label} must be declared at the root of the version, outside object, collection, one_of and conditions" unless current_scope.is_a?(Version)
381
+
382
+ send(as, name, **options)
383
+ current_scope.add_filter(name, block)
384
+ end
385
+
339
386
  # Defines a oneOf property for polymorphic schemas
340
387
  #
341
388
  # Creates a JSON Schema oneOf structure where exactly one of the defined
@@ -366,6 +413,36 @@ module Verquest
366
413
  @current_scope = previous_scope if block_given?
367
414
  end
368
415
 
416
+ # Errors for root keys that only another version declares
417
+ #
418
+ # @param params [Hash] The params being processed
419
+ # @param version [Verquest::Version] The resolved version
420
+ # @return [Array<Hash>] One error per key, in the format of validation errors
421
+ def other_version_key_errors(params, version)
422
+ other_names = versions.property_names - version.all_properties.keys
423
+
424
+ params.keys.filter_map do |key|
425
+ key = key.to_s
426
+ next unless other_names.include?(key)
427
+
428
+ {pointer: "/#{key}", type: "other_version", message: "`#{key}` isn't available in version #{version.name}", details: nil}
429
+ end
430
+ end
431
+
432
+ # Reports failed params according to the validation_error_handling setting
433
+ #
434
+ # @param errors [Array<Hash>] The errors
435
+ # @return [Verquest::Result] A failure, when validation_error_handling is :result
436
+ # @raise [Verquest::InvalidParamsError] When validation_error_handling is :raise
437
+ def validation_failure(errors)
438
+ case Verquest.configuration.validation_error_handling
439
+ when :raise
440
+ raise InvalidParamsError.new("Validation failed", errors:)
441
+ when :result
442
+ Result.failure(errors)
443
+ end
444
+ end
445
+
369
446
  # Adds a property to the current scope
370
447
  #
371
448
  # @param property [Verquest::Properties::Base] The property to add
@@ -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`)
@@ -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
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Verquest
4
- GEM_VERSION = "0.8.0"
4
+ GEM_VERSION = "0.9.0"
5
5
  end
@@ -46,7 +46,10 @@ module Verquest
46
46
  #
47
47
  # @!attribute [r] location
48
48
  # @return [Symbol] Where the params come from, `:body`, `:query` or `:path`
49
- attr_reader :name, :properties, :schema, :validation_schema, :mapping, :transformer, :external_mapping, :location
49
+ #
50
+ # @!attribute [r] filters
51
+ # @return [Hash{String => Proc}] Filter blocks by property name, in declaration order
52
+ attr_reader :name, :properties, :filters, :schema, :validation_schema, :mapping, :transformer, :external_mapping, :location
50
53
 
51
54
  # @!attribute [rw] schema_options
52
55
  # @return [Hash] Additional JSON schema options for this version
@@ -65,6 +68,7 @@ module Verquest
65
68
  @location = location
66
69
  @schema_options = {}
67
70
  @properties = {}
71
+ @filters = {}
68
72
  @conditions = []
69
73
  # Filled after the version is frozen, so it is created here; freeze is shallow
70
74
  @validation_schemers = {}
@@ -73,19 +77,33 @@ module Verquest
73
77
 
74
78
  # Add a property to this version
75
79
  #
80
+ # A property added under the name of a filter replaces the filter too, so a plain property over an
81
+ # inherited filter stops filtering.
82
+ #
76
83
  # @param property [Verquest::Properties::Base] The property to add
77
84
  # @return [Verquest::Properties::Base] The added property
78
85
  def add(property)
79
86
  check_unnamed_one_of(property)
87
+ filters.delete(property.name)
80
88
  properties[property.name] = property
81
89
  end
82
90
 
83
- # Remove a property from this version by name
91
+ # Store the block that filters by a property's value
92
+ #
93
+ # @param name [Symbol, String] The name of the property the filter reads
94
+ # @param block [Proc] Called with the target and the property's processed value, returns the filtered target
95
+ # @return [Proc] The stored block
96
+ def add_filter(name, block)
97
+ filters[name.to_s] = block
98
+ end
99
+
100
+ # Remove a property, and its filter, from this version by name
84
101
  #
85
102
  # @param property_name [Symbol, String] The name of the property to remove
86
103
  # @return [Verquest::Properties::Base] The removed property
87
104
  # @raise [PropertyNotFoundError] If the property doesn't exist
88
105
  def remove(property_name)
106
+ filters.delete(property_name.to_s)
89
107
  properties.delete(property_name.to_s) || raise(PropertyNotFoundError.new("Property '#{property_name}' is not defined on '#{name}'"))
90
108
  end
91
109
 
@@ -120,6 +138,7 @@ module Verquest
120
138
  next if exclude_properties.include?(property.name.to_sym)
121
139
 
122
140
  add(property)
141
+ add_filter(property.name, version.filters[property.name]) if version.filters.key?(property.name)
123
142
  end
124
143
 
125
144
  version.conditions.each { |condition| add_condition(condition) }
@@ -151,7 +170,9 @@ module Verquest
151
170
  end
152
171
 
153
172
  prepare_parameters if parameters?
173
+ @property_defaults = property_defaults?(validation_schema)
154
174
  @transformer = Transformer.new(layout: transformer_layout)
175
+ @filters.freeze
155
176
  freeze
156
177
  end
157
178
 
@@ -193,6 +214,8 @@ module Verquest
193
214
 
194
215
  # Validate request parameters against the version's validation schema
195
216
  #
217
+ # Inserts missing defaults into params when {#inserts_property_defaults?} is true.
218
+ #
196
219
  # @param params [Hash] The request parameters to validate
197
220
  # @return [Array<Hash>] An array of validation error details, or empty if valid
198
221
  def validate_params(params:)
@@ -206,6 +229,13 @@ module Verquest
206
229
  end
207
230
  end
208
231
 
232
+ # Check if validating params inserts the defaults the schema declares
233
+ #
234
+ # @return [Boolean] true when the schema declares a default and the configuration inserts defaults
235
+ def inserts_property_defaults?
236
+ !!insert_property_defaults_setting
237
+ end
238
+
209
239
  # Get the mapping for a specific property
210
240
  #
211
241
  # @param property [Symbol, String] The property name (regular or declared in a condition branch)
@@ -322,19 +352,26 @@ module Verquest
322
352
  # Returns the compiled validation schema for the current configuration
323
353
  #
324
354
  # Compiling is much slower than validating, so each configuration is
325
- # compiled once and reused. The lock keeps threads from compiling at the
326
- # same time.
355
+ # compiled once and reused. Default insertion is turned off when the schema
356
+ # declares no default, since json_schemer would walk every result for
357
+ # nothing. The lock keeps threads from compiling at the same time.
327
358
  #
328
359
  # @return [JSONSchemer::Schema] The compiled validation schema
329
360
  def validation_schemer
330
- configuration = Verquest.configuration
331
- key = [configuration.json_schema_uri, configuration.insert_property_defaults]
361
+ key = [Verquest.configuration.json_schema_uri, insert_property_defaults_setting]
332
362
 
333
363
  @validation_schemers_lock.synchronize do
334
364
  @validation_schemers[key] ||= JSONSchemer.schema(validation_schema, meta_schema: key[0], insert_property_defaults: key[1])
335
365
  end
336
366
  end
337
367
 
368
+ # Returns the insert_property_defaults value to compile with
369
+ #
370
+ # @return [Boolean, Symbol] The configured value when the schema declares a default, false otherwise
371
+ def insert_property_defaults_setting
372
+ @property_defaults ? Verquest.configuration.insert_property_defaults : false
373
+ end
374
+
338
375
  # Generates the JSON schema for this version
339
376
  #
340
377
  # Creates a schema object with type, description, required properties,
@@ -409,6 +446,20 @@ module Verquest
409
446
  @validation_schema = properties.values.first.to_validation_schema(version: name)
410
447
  end
411
448
 
449
+ # Checks whether a schema declares a default anywhere
450
+ #
451
+ # A property named `default` also counts, which only keeps default insertion on.
452
+ #
453
+ # @param schema [Object] The schema or a part of it
454
+ # @return [Boolean] true if any Hash in it has a "default" key
455
+ def property_defaults?(schema)
456
+ case schema
457
+ when Hash then schema.key?("default") || schema.each_value.any? { |value| property_defaults?(value) }
458
+ when Array then schema.any? { |value| property_defaults?(value) }
459
+ else false
460
+ end
461
+ end
462
+
412
463
  # Prepares the parameter mapping for this version
413
464
  #
414
465
  # Collects mappings from all properties in this version and checks for
@@ -40,6 +40,7 @@ module Verquest
40
40
  def add(version)
41
41
  raise ArgumentError, "Expected a Verquest::Version instance" unless version.is_a?(Verquest::Version)
42
42
 
43
+ @property_names = nil
43
44
  versions[version.name] = version
44
45
  end
45
46
 
@@ -63,6 +64,15 @@ module Verquest
63
64
  versions.keys.sort
64
65
  end
65
66
 
67
+ # Returns the root property names declared by any version
68
+ #
69
+ # Cached until the next version is added.
70
+ #
71
+ # @return [Array<String>] The property names
72
+ def property_names
73
+ @property_names ||= versions.values.flat_map { |version| version.all_properties.keys }.uniq.freeze
74
+ end
75
+
66
76
  private
67
77
 
68
78
  # @!attribute [r] versions
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: verquest
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.0
4
+ version: 0.9.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Petr Hlavicka
@@ -122,6 +122,7 @@ metadata:
122
122
  homepage_uri: https://github.com/verquest/verquest
123
123
  source_code_uri: https://github.com/verquest/verquest
124
124
  changelog_uri: https://github.com/verquest/verquest/blob/main/CHANGELOG.md
125
+ rubygems_mfa_required: 'true'
125
126
  rdoc_options: []
126
127
  require_paths:
127
128
  - lib