resteze 1.0.0 → 1.1.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.
@@ -0,0 +1,241 @@
1
+ # Building a Client
2
+
3
+ This is the task-oriented guide: you have an API, and you want a client gem for
4
+ it. The other files in `docs/` are reference, organized by feature. Start here,
5
+ and follow the links when you need the detail.
6
+
7
+ It is written for people and for AI coding agents alike. If you are an agent,
8
+ read [What not to do](#what-not-to-do) before you write code.
9
+
10
+ ## Table of Contents
11
+
12
+ - [Before you write code](#before-you-write-code)
13
+ - [What the API looks like, and what to use](#what-the-api-looks-like-and-what-to-use)
14
+ - [A complete client](#a-complete-client)
15
+ - [What not to do](#what-not-to-do)
16
+ - [Testing the client](#testing-the-client)
17
+ - [Where to read more](#where-to-read-more)
18
+
19
+ ## Before you write code
20
+
21
+ Answer these about the API. Each answer picks a feature in the next section.
22
+
23
+ 1. **How are paths shaped?** Is the id in the path (`/widgets/42`), or are
24
+ endpoints named by verb (`/widgets/details?widget_id=42`)?
25
+ 2. **Does any resource live under another?** For example
26
+ `/catalogs/shoes/items`.
27
+ 3. **Which operations exist beyond read, list, create, update and delete?**
28
+ 4. **What does a list response look like?** Which key holds the items, and
29
+ what else comes back beside them?
30
+ 5. **Are single records wrapped in an envelope**, such as `{ "widget": {...} }`?
31
+ 6. **How does it authenticate?** A key in a header or query param, HTTP Basic,
32
+ a bearer token, a client certificate, or something else.
33
+ 7. **Which statuses mean failure, and can a 2xx carry an error in its body?**
34
+ 8. **How does it rate-limit, and should the client retry a 429?**
35
+ 9. **What should callers rescue?** `rescue MyApi::Error` is the catch-all.
36
+ Name the specific classes they will want: `RateLimitError`,
37
+ `AuthenticationError`, `ResourceNotFound`.
38
+
39
+ ## What the API looks like, and what to use
40
+
41
+ | The API... | Use | Read |
42
+ |---|---|---|
43
+ | puts the id in the path and uses GET, POST and PUT conventionally | Nothing. Paths come from the class name. | [API.md](API.md) |
44
+ | names a resource differently from its class | `def self.resource_slug` on the resource, or `default_resource_slug(klass)` on the module | [API.md](API.md) |
45
+ | has a path prefix or a version segment | `default_service_path(klass)` and `default_api_version(klass)` on the module | [API.md](API.md) |
46
+ | has a list endpoint | `include List` on the resource | [ADVANCED_USAGE.md](ADVANCED_USAGE.md) |
47
+ | creates and updates records | `include Save` on the resource | [ADVANCED_USAGE.md](ADVANCED_USAGE.md) |
48
+ | deletes records | `include Destroy` on the resource | [ADVANCED_USAGE.md](ADVANCED_USAGE.md) |
49
+ | returns list items under a key other than `data` | `def self.list_key` on the resource, or `default_list_key(klass)` on the module | [API.md](API.md) |
50
+ | wraps a single record in an envelope | `def self.object_key` on the resource, or `default_object_key(klass)` on the module | [API.md](API.md) |
51
+ | has an operation beyond the standard five | `action :name, method: :post` (add `on: :member` when it acts on one record) | [ACTIONS.md](ACTIONS.md) |
52
+ | addresses the standard operations by verb, or sends the id as a param | Re-route them: `action :retrieve, path: "details", id: :param`. Set it once for every resource with module-level `action` and `action_defaults` | [ACTIONS.md](ACTIONS.md) |
53
+ | nests a resource under a parent | `path_template "catalogs/:catalog_name/items"` | [NESTED_RESOURCES.md](NESTED_RESOURCES.md) |
54
+ | authenticates with a key, Basic, a bearer token or a client certificate | `authenticate_with :api_key`, `:basic`, `:bearer` or `:mtls` on the module | [CONFIGURATION.md](CONFIGURATION.md#authentication) |
55
+ | authenticates some other way | A `Resteze::Authenticator::Strategy` subclass, passed to `authenticate_with` | [CONFIGURATION.md](CONFIGURATION.md#writing-a-scheme) |
56
+ | reports failures inside a 2xx body | Override `Response.body_error` in the module | [ERROR_HANDLING.md](ERROR_HANDLING.md) |
57
+ | rate-limits | `rate_limit_with :fixed_window`, `:sliding_window`, `:token_bucket` or `:leaky_bucket` on the module | [CONFIGURATION.md](CONFIGURATION.md#rate-limits) |
58
+ | should be retried after a 429 | Override `retry?` in the module's `RateLimiter` | [CONFIGURATION.md](CONFIGURATION.md#retrying-after-a-429) |
59
+ | needs a setting Resteze does not ship | `attr_accessor` on the module's singleton class | [CONFIGURATION.md](CONFIGURATION.md#custom-configuration-properties) |
60
+
61
+ If nothing in the table fits one endpoint, a resource is an ordinary class and
62
+ `request(:post, path, params: {...})` is available on it. Use that for the
63
+ one-off, not as the default.
64
+
65
+ ## A complete client
66
+
67
+ Every feature in this example is optional except `include Resteze`.
68
+
69
+ ```ruby
70
+ require "resteze"
71
+
72
+ module WidgetApi
73
+ include Resteze
74
+
75
+ # Authentication. :bearer reads the token from WidgetApi.api_key, a setting
76
+ # this line declares.
77
+ authenticate_with :bearer
78
+
79
+ # Pacing: at most 100 requests per 60 seconds, per process.
80
+ rate_limit_with :fixed_window, limit: 100, window: 60
81
+
82
+ # This API returns list items under the resource's own name.
83
+ def self.default_list_key(klass)
84
+ klass.resource_slug.to_sym
85
+ end
86
+
87
+ # This API reports some failures inside a 200.
88
+ class Response
89
+ def self.body_error(response)
90
+ data = response.data
91
+ return unless data.is_a?(Hash) && data[:errors].present?
92
+
93
+ ApiError.from_response(response, data[:message])
94
+ end
95
+ end
96
+
97
+ # A plain REST resource: nothing to route.
98
+ # GET /widgets, GET /widgets/42, POST /widgets, PUT /widgets/42,
99
+ # DELETE /widgets/42
100
+ class Widget < ApiResource
101
+ include List
102
+ include Save
103
+ include Destroy
104
+
105
+ property :id
106
+ property :name
107
+ property :status
108
+ property :created_at, transform_with: ->(value) { Time.parse(value) }
109
+
110
+ # POST /widgets/42/archive
111
+ action :archive, method: :post, on: :member
112
+ # GET /widgets/search?q=... returning a list of widgets
113
+ action :search, method: :get, returns: :list
114
+ end
115
+
116
+ # A resource whose standard operations are addressed by verb.
117
+ # GET /campaigns/details?campaign_id=42
118
+ class Campaign < ApiResource
119
+ property :id
120
+ property :name
121
+
122
+ action :retrieve, path: "details", id: :param
123
+ end
124
+
125
+ # A nested resource.
126
+ # GET /catalogs/shoes/items, GET /catalogs/shoes/items/sku1
127
+ class Item < ApiResource
128
+ include List
129
+ include Save
130
+
131
+ property :id
132
+ property :price
133
+
134
+ path_template "catalogs/:catalog_name/items"
135
+ end
136
+
137
+ class Catalog < ApiResource
138
+ property :name
139
+
140
+ def items(params: {})
141
+ Item.list(catalog_name: name, parent: self, params:)
142
+ end
143
+ end
144
+ end
145
+
146
+ WidgetApi.configure do |config|
147
+ config.api_base = "https://api.widgets.example/"
148
+ config.api_key = ENV.fetch("WIDGET_API_KEY", nil)
149
+ config.open_timeout = 5
150
+ config.read_timeout = 15
151
+ end
152
+ ```
153
+
154
+ Calling it:
155
+
156
+ ```ruby
157
+ widget = WidgetApi::Widget.retrieve(42)
158
+ widget.name = "Large sprocket"
159
+ widget.save
160
+ widget.archive
161
+ widget.destroy
162
+
163
+ WidgetApi::Widget.list(params: { page: 2 })
164
+ WidgetApi::Widget.search(q: "sprocket")
165
+
166
+ WidgetApi::Campaign.retrieve(42)
167
+
168
+ WidgetApi::Item.list(catalog_name: "shoes")
169
+ WidgetApi::Item.retrieve("sku1", catalog_name: "shoes")
170
+
171
+ begin
172
+ WidgetApi::Widget.retrieve(999)
173
+ rescue WidgetApi::ResourceNotFound
174
+ nil
175
+ rescue WidgetApi::RateLimitError => e
176
+ sleep(e.retry_after || 1)
177
+ retry
178
+ rescue WidgetApi::Error => e
179
+ warn "#{e.http_status}: #{e.message}"
180
+ end
181
+ ```
182
+
183
+ `include Resteze` creates `WidgetApi::ApiResource`, `WidgetApi::Client`,
184
+ `WidgetApi::Response`, `WidgetApi::Error` and the rest, so inside the module
185
+ you refer to them by their short names.
186
+
187
+ ## What not to do
188
+
189
+ Each of these works against something Resteze already does.
190
+
191
+ | Don't | Do instead | Why |
192
+ |---|---|---|
193
+ | Override `resource_path`, `list`, `list_resource_path` or `retrieve_params` to reach a nested path | `path_template` | Overrides bypass the action registry, so re-routed and custom actions stop nesting. |
194
+ | Hand-write a class method that calls `request` for each extra endpoint | `action` | The DSL validates the declaration, generates both class and instance forms, and is visible to `has_action` in tests. |
195
+ | Build URLs with string interpolation | Let `resource_path` and `action` build them | Ids and path values are percent-encoded for you; interpolation is not. |
196
+ | `rescue Faraday::Error` or any `Faraday::` class | `rescue WidgetApi::Error` and its subclasses | Every failure is mapped onto the module's own hierarchy. The Faraday error is `e.cause`. |
197
+ | `rescue Resteze::Error` to catch one API's errors | `rescue WidgetApi::Error` | Each module has its own hierarchy so that two clients in one process stay apart. |
198
+ | Inherit from `Resteze::Object` or look for a `Resteze::ApiResource` class | `class Widget < ApiResource` inside the module | The per-module classes are what know which client and configuration to use. |
199
+ | Set headers or credentials in each resource | `authenticate_with` on the module | It is applied to every request, retried once on a 401 when the scheme can refresh, and masked in the debug log. |
200
+ | Sleep and retry on a 429 inside resources | `rate_limit_with` and `retry?` on the module's `RateLimiter` | The limiter is shared across threads and consulted before each request. |
201
+ | Put a parent's id into `params:` for a nested resource | Pass it as a path keyword: `Item.list(catalog_name: "shoes")` | Path values never reach the query string or body. |
202
+ | Store per-request state on a resource class | Keep it on instances | Classes are shared by every thread. |
203
+ | Declare every field the API returns | Declare the ones you use | Undeclared keys are kept in the property bag, so a new field never breaks an old client. |
204
+
205
+ ## Testing the client
206
+
207
+ Use WebMock for requests and the helpers in `lib/resteze/testing/` for
208
+ declarations. `has_property` and `has_action` assert what a resource declares
209
+ without making a request:
210
+
211
+ ```ruby
212
+ require "resteze/testing/minitest"
213
+
214
+ class WidgetTest < Minitest::Spec
215
+ include Resteze::Testing::Minitest::Object
216
+
217
+ subject { WidgetApi::Widget }
218
+
219
+ it "declares its properties and routes" do
220
+ has_property :id
221
+ has_property :created_at, transformed: true
222
+ has_action :archive, method: :post, on: :member, path: "/widgets/ID/archive"
223
+ has_action :retrieve, path: "/widgets/ID"
224
+ end
225
+ end
226
+ ```
227
+
228
+ `require "resteze/testing/rspec"` provides the same helpers for RSpec. See
229
+ [TESTING.md](TESTING.md).
230
+
231
+ ## Where to read more
232
+
233
+ | File | Covers |
234
+ |---|---|
235
+ | [API.md](API.md) | Core concepts, resources, properties, requests and responses |
236
+ | [ACTIONS.md](ACTIONS.md) | The `action` DSL: custom actions, re-routing, defaults, return values |
237
+ | [NESTED_RESOURCES.md](NESTED_RESOURCES.md) | `path_template`, path values, the `parent:` reference |
238
+ | [CONFIGURATION.md](CONFIGURATION.md) | Settings, authentication, connections, logging, rate limits |
239
+ | [ERROR_HANDLING.md](ERROR_HANDLING.md) | The error hierarchy, what an error carries, `body_error` |
240
+ | [ADVANCED_USAGE.md](ADVANCED_USAGE.md) | Lists, saves, pagination and batching patterns |
241
+ | [TESTING.md](TESTING.md) | Minitest and RSpec helpers, WebMock and VCR |
@@ -236,7 +236,7 @@ end
236
236
 
237
237
  ### Using Configuration Files
238
238
 
239
- ```ruby
239
+ ```yaml
240
240
  # config/my_api.yml
241
241
  production:
242
242
  api_base: "https://api.example.com/"
@@ -642,7 +642,7 @@ The instance is `MyApi.rate_limiter`; assign one to replace it. Each attempt of
642
642
  The four common algorithms are built in. Pick one with `strategy` in your module's `RateLimiter`:
643
643
 
644
644
  ```ruby
645
- module Braze
645
+ module CampaignApi
646
646
  class RateLimiter
647
647
  strategy :fixed_window, limit: 250_000, window: 3600, headers: true
648
648
  end
@@ -651,7 +651,7 @@ end
651
651
 
652
652
  | Strategy | Options | Behaviour |
653
653
  |---|---|---|
654
- | `:fixed_window` | `limit:`, `window:` seconds, `headers:`, `reset:` | At most `limit` requests per window, windows aligned to the first request. With `headers: true` the budget and window follow the API's `X-RateLimit-Limit`, `-Remaining` and `-Reset` headers, which is how Braze and JD Power report theirs; pass a Hash to name other headers, and `reset: :seconds` when the reset header is a countdown rather than a time. `limit:` may be omitted when the API sends it, or sends only the remaining count. Syncing is conservative: within a window the lower of the local and reported remaining counts wins, since requests admitted after the server answered are not in its number yet; a reset beyond the local window starts a fresh one; non-finite or far-future resets are not trusted |
654
+ | `:fixed_window` | `limit:`, `window:` seconds, `headers:`, `reset:` | At most `limit` requests per window, windows aligned to the first request. With `headers: true` the budget and window follow the API's `X-RateLimit-Limit`, `-Remaining` and `-Reset` headers, which is how many APIs report theirs; pass a Hash to name other headers, and `reset: :seconds` when the reset header is a countdown rather than a time. `limit:` may be omitted when the API sends it, or sends only the remaining count. Syncing is conservative: within a window the lower of the local and reported remaining counts wins, since requests admitted after the server answered are not in its number yet; a reset beyond the local window starts a fresh one; non-finite or far-future resets are not trusted |
655
655
  | `:sliding_window` | `limit:`, `window:` seconds | At most `limit` requests in any trailing window. Exact; memory bounded by `limit` |
656
656
  | `:token_bucket` | `capacity:`, `refill_rate:` per second | Bursts up to `capacity`, then paced at the refill rate |
657
657
  | `:leaky_bucket` | `capacity:`, `leak_rate:` per second | Smooths bursts into a steady rate; a full bucket waits for room |
@@ -711,7 +711,7 @@ end
711
711
  A strategy keeps you under the limit; `retry?` and `retry_after` say what to do when the API disagrees. Override them alongside, or instead of, a strategy:
712
712
 
713
713
  ```ruby
714
- module Braze
714
+ module CampaignApi
715
715
  class RateLimiter
716
716
  strategy :fixed_window, limit: 250_000, window: 3600, headers: true
717
717
 
@@ -735,7 +735,7 @@ end
735
735
  With a strategy, `before_request` waits in the calling thread by default (`on_wait: :sleep`). A background job would often rather give the thread back and reschedule itself. `on_wait: :raise` makes the limiter raise `MyApi::RateLimitError` instead of waiting, with the computed wait in `retry_after` and no `http_status`, since nothing was sent. An error raised this way never goes through `retry?`; it is a refusal, not a failed attempt.
736
736
 
737
737
  ```ruby
738
- module Braze
738
+ module CampaignApi
739
739
  class RateLimiter
740
740
  strategy :fixed_window, limit: 250_000, window: 3600, headers: true, on_wait: :raise
741
741
  end
@@ -749,7 +749,7 @@ class TrackEventsJob
749
749
  end
750
750
 
751
751
  def perform(events)
752
- Braze::User.track(events:) # a spent budget, or a 429, raises; Sidekiq reschedules
752
+ CampaignApi::User.track(events:) # a spent budget, or a 429, raises; Sidekiq reschedules
753
753
  end
754
754
  end
755
755
  ```
@@ -767,7 +767,7 @@ strategy :fixed_window, limit: 1000, window: 60, max_wait: 120
767
767
  Any method can be overridden; call `super` to keep the strategy's behaviour. State belongs in the limiter's mutex-guarded hash, never in instance variables, so a subclass stays thread-safe without doing anything: `state` returns a snapshot, `update_state` merges values, and `synchronize { |state| ... }` yields the live hash for read-modify-write sequences.
768
768
 
769
769
  ```ruby
770
- module Braze
770
+ module CampaignApi
771
771
  class RateLimiter
772
772
  strategy :fixed_window, limit: 250_000, window: 3600, headers: true
773
773
 
@@ -314,7 +314,7 @@ user = RetryableRequest.execute { MyApi::User.retrieve('123') }
314
314
 
315
315
  ## Errors Reported in a 2xx Body
316
316
 
317
- Some APIs answer with a successful HTTP status and put the failure in the body. Braze, for example, returns `201 Created` with `{"message": "success", "errors": [...]}` when some records in a batch were rejected, and `200 OK` with `{"message": "Invalid API key"}` for others. The status-based middleware cannot see these.
317
+ Some APIs answer with a successful HTTP status and put the failure in the body. A messaging API might return `201 Created` with `{"message": "success", "errors": [...]}` when some records in a batch were rejected, and `200 OK` with `{"message": "Invalid API key"}` for others. The status-based middleware cannot see these.
318
318
 
319
319
  Override `body_error` on your module's `Response`. It receives the parsed `Response` after the middleware has accepted the status. Return an exception to raise it, or `nil` to accept the response. `Error.from_response` builds a namespaced error that carries the status, headers, body and parsed `json_body`, with the `Response` itself as `e.response`:
320
320
 
@@ -0,0 +1,237 @@
1
+ # Nested Resources
2
+
3
+ Some resources only exist under a parent:
4
+
5
+ ```
6
+ GET /catalogs/:catalog_name/items
7
+ GET /catalogs/:catalog_name/items/:id
8
+ POST /catalogs/:catalog_name/items/:id/archive
9
+ ```
10
+
11
+ Declare the path once with `path_template`. `retrieve`, `list`, `save`,
12
+ `destroy`, `refresh` and every custom action then route under it, with nothing
13
+ to override.
14
+
15
+ ```ruby
16
+ module WidgetApi
17
+ include Resteze
18
+
19
+ class Item < ApiResource
20
+ include WidgetApi::List
21
+ include WidgetApi::Save
22
+
23
+ property :id
24
+ property :price
25
+
26
+ path_template "catalogs/:catalog_name/items"
27
+
28
+ action :archive, method: :post, on: :member
29
+ action :bulk_update, method: :post
30
+ end
31
+ end
32
+ ```
33
+
34
+ ## Table of Contents
35
+
36
+ - [The template](#the-template)
37
+ - [Calling a nested resource](#calling-a-nested-resource)
38
+ - [What an instance remembers](#what-an-instance-remembers)
39
+ - [Actions](#actions)
40
+ - [The parent reference](#the-parent-reference)
41
+ - [Errors](#errors)
42
+ - [Testing](#testing)
43
+
44
+ ## The template
45
+
46
+ - The template is the resource's whole path, in place of its slug. The service
47
+ path and API version still go in front, and the id still goes behind.
48
+ - A segment written `:name` is a **path value** that each call fills in. A
49
+ token is a whole segment and is named like a method (`:catalog_name`).
50
+ Everything else is used as written.
51
+ - Any number of tokens is allowed:
52
+ `path_template "catalogs/:catalog_name/items/:item_id/variants"`.
53
+ - Subclasses inherit the template and may declare their own.
54
+ - `Item.path_template` returns the template and `Item.path_tokens` its token
55
+ names, `[:catalog_name]`. The values belong to an instance: `item.path_params`
56
+ is `{ catalog_name: "shoes" }`.
57
+ - `Item.nested?` is true for a resource with a template and false for any
58
+ other. Instances answer it too (`item.nested?`).
59
+ - `resource_slug` is unchanged (`"items"`), so defaults derived from it, such
60
+ as the id param name, stay the same.
61
+
62
+ These are rejected with an `ArgumentError` when the class is loaded:
63
+
64
+ | Template | Why |
65
+ |---|---|
66
+ | `"catalogs/items"` | No tokens. Set `resource_slug` instead. |
67
+ | `"a/:x/b/:x"` | A token is repeated. |
68
+ | `"things/:id/parts"` | `id`, `params`, `values` and `parent` are reserved. |
69
+ | `"catalogs/v:version/items"` | A token must be a whole segment. |
70
+ | `"catalogs/../:name/items"` | A literal segment cannot be `.` or `..`. |
71
+ | `"stores/:key/items"` | The reader `#key` would shadow an existing method. Resources are Hashes, so pick another name, such as `:store_key`. |
72
+
73
+ ## Calling a nested resource
74
+
75
+ Path values are keywords, separate from request params:
76
+
77
+ ```ruby
78
+ WidgetApi::Item.list(catalog_name: "shoes", params: { cursor: "abc" })
79
+ # => GET /catalogs/shoes/items?cursor=abc
80
+
81
+ WidgetApi::Item.retrieve("sku1", catalog_name: "shoes")
82
+ # => GET /catalogs/shoes/items/sku1
83
+
84
+ WidgetApi::Item.new(catalog_name: "shoes", values: { price: 10 }).save
85
+ # => POST /catalogs/shoes/items body: {"price":10}
86
+
87
+ WidgetApi::Item.new("sku1", catalog_name: "shoes", values: { price: 12 }).save
88
+ # => PUT /catalogs/shoes/items/sku1
89
+
90
+ WidgetApi::Item.destroy("sku1", catalog_name: "shoes") # with `include Destroy`
91
+ # => DELETE /catalogs/shoes/items/sku1
92
+ ```
93
+
94
+ Path values are percent-encoded the same way the id is (`"red shoes"` is sent
95
+ as `red%20shoes`), and they never appear in the query string or the request
96
+ body.
97
+
98
+ The hash form of `retrieve` works too. Path values are taken out first and the
99
+ rest is the id and its extra params:
100
+
101
+ ```ruby
102
+ WidgetApi::Item.retrieve(id: "sku1", catalog_name: "shoes", expand: true)
103
+ # => GET /catalogs/shoes/items/sku1?expand=true
104
+ ```
105
+
106
+ A keyword that is not one of the template's tokens raises `ArgumentError`, as
107
+ any unknown keyword does. A resource with no template accepts no path
108
+ keywords at all.
109
+
110
+ ## What an instance remembers
111
+
112
+ Every instance keeps the path values it was built with, so it can route by
113
+ itself later:
114
+
115
+ ```ruby
116
+ items = WidgetApi::Item.list(catalog_name: "shoes")
117
+ item = items.first
118
+
119
+ item.catalog_name # => "shoes"
120
+ item.path_params # => { catalog_name: "shoes" } (frozen)
121
+ item.refresh # => GET /catalogs/shoes/items/sku1
122
+ item.save # => PUT /catalogs/shoes/items/sku1
123
+ item.destroy # => DELETE /catalogs/shoes/items/sku1
124
+ ```
125
+
126
+ - Items in a list get the path values of the `list` call that produced them.
127
+ So do the results of actions that return this resource (`returns: :self`,
128
+ `returns: :list`, or the class itself). Results of any other class do not.
129
+ - The values live beside the properties, not in them. They are not part of
130
+ `as_json` or the save body.
131
+ - `refresh` and `save` leave them in place.
132
+ - One reader is generated per token.
133
+
134
+ If the API echoes the parent's id in the body and you declare it as a
135
+ property, the property keeps its reader. For routing, a value passed
136
+ explicitly wins and the property is the fallback:
137
+
138
+ ```ruby
139
+ class Field < ApiResource
140
+ property :id
141
+ property :catalog_name
142
+ path_template "catalogs/:catalog_name/fields"
143
+ end
144
+
145
+ Field.new("f1", values: { catalog_name: "shoes" }).resource_path
146
+ # => "/catalogs/shoes/fields/f1"
147
+ ```
148
+
149
+ ## Actions
150
+
151
+ Custom actions nest like the built-ins, including re-routed ones and those
152
+ that carry the id as a param.
153
+
154
+ ```ruby
155
+ WidgetApi::Item.bulk_update(catalog_name: "shoes", items: [{ id: "sku1", price: 9 }])
156
+ # => POST /catalogs/shoes/items/bulk_update body: {"items":[{"id":"sku1","price":9}]}
157
+
158
+ WidgetApi::Item.archive("sku1", catalog_name: "shoes", reason: "old")
159
+ # => POST /catalogs/shoes/items/sku1/archive body: {"reason":"old"}
160
+
161
+ item.archive(reason: "old")
162
+ # => the same request, using the values the item remembers
163
+ ```
164
+
165
+ The class forms read the template's tokens (and `parent:`) from their keywords
166
+ as path values; everything else is a request param.
167
+
168
+ The instance form never takes path values. Every keyword is a request param,
169
+ which is also how you send a param that shares a token's name:
170
+
171
+ ```ruby
172
+ item.move(catalog_name: "boots")
173
+ # => POST /catalogs/shoes/items/sku1/move body: {"catalog_name":"boots"}
174
+ ```
175
+
176
+ ## The parent reference
177
+
178
+ Resteze has no associations. The parent side is a method you write, and it can
179
+ hand itself over with `parent:`:
180
+
181
+ ```ruby
182
+ class Catalog < ApiResource
183
+ property :name
184
+
185
+ def items(params: {})
186
+ Item.list(catalog_name: name, parent: self, params:)
187
+ end
188
+ end
189
+
190
+ catalog.items.first.parent.equal?(catalog) # => true
191
+ ```
192
+
193
+ - `parent:` is accepted wherever path values are: `list`, `retrieve`, `new`,
194
+ `destroy` and the class forms of actions.
195
+ - It travels with the path values: every item in a list gets it, and it
196
+ survives `refresh` and `save`.
197
+ - It is only a reference. Resteze never fetches it, never serializes it, and
198
+ never reads path values from it, so pass those as well.
199
+ - `item.parent` is `nil` when none was given.
200
+ - If the resource declares a property named `parent`, the property keeps that
201
+ reader and the reference is available as `item.path_parent`.
202
+
203
+ ## Errors
204
+
205
+ A path value may be missing when an object is built. It is checked when a
206
+ path is needed, before any request is sent:
207
+
208
+ ```ruby
209
+ WidgetApi::Item.list
210
+ # => WidgetApi::InvalidRequestError, param: "catalog_name"
211
+
212
+ WidgetApi::Item.new("sku1").refresh
213
+ # => WidgetApi::InvalidRequestError, param: "catalog_name"
214
+ ```
215
+
216
+ A blank value (`nil` or `""`) counts as missing. So does `"."` or `".."`, which a URL would
217
+ resolve as a directory step out of the template's path. The id is held to the
218
+ same rule.
219
+
220
+ ## Testing
221
+
222
+ `has_action ... path:` fills each token with its upcased name, the way it uses
223
+ `"ID"` for the id:
224
+
225
+ ```ruby
226
+ describe WidgetApi::Item do
227
+ include Resteze::Testing::Minitest::Object
228
+
229
+ subject { WidgetApi::Item }
230
+
231
+ it "routes its actions" do
232
+ has_action :retrieve, path: "/catalogs/CATALOG_NAME/items/ID"
233
+ has_action :archive, method: :post, on: :member, path: "/catalogs/CATALOG_NAME/items/ID/archive"
234
+ has_action :bulk_update, path: "/catalogs/CATALOG_NAME/items/bulk_update"
235
+ end
236
+ end
237
+ ```
data/docs/TESTING.md CHANGED
@@ -182,6 +182,13 @@ class CampaignTest < Minitest::Spec
182
182
  end
183
183
  ```
184
184
 
185
+ For a nested resource (one that declares a `path_template`), each token is
186
+ filled with its upcased name:
187
+
188
+ ```ruby
189
+ has_action :archive, path: "/catalogs/CATALOG_NAME/items/ID/archive"
190
+ ```
191
+
185
192
  ### Testing Lists
186
193
 
187
194
  ```ruby
@@ -288,6 +295,26 @@ class UserSaveTest < ApiTestCase
288
295
  end
289
296
  ```
290
297
 
298
+ ### Testing Destroy Operations
299
+
300
+ ```ruby
301
+ class UserDestroyTest < ApiTestCase
302
+ def test_destroy_user
303
+ stub_api_request(:delete, '/users/123').to_return(status: 204, body: '')
304
+
305
+ result = TestApi::User.destroy('123')
306
+
307
+ assert_requested :delete, api_url('/users/123')
308
+ assert_empty result
309
+ assert_equal 204, result.http_response.http_status
310
+ end
311
+
312
+ def test_destroy_requires_an_id
313
+ assert_raises(TestApi::InvalidRequestError) { TestApi::User.new.destroy }
314
+ end
315
+ end
316
+ ```
317
+
291
318
  ## Integration Testing
292
319
 
293
320
  ### Full Request Cycle Testing
@@ -3,14 +3,15 @@ module Resteze
3
3
  # type for one named operation such as :retrieve or :track.
4
4
  class Action
5
5
  OPTIONS = %i[method on path id id_param returns as].freeze
6
- RESERVED = %i[retrieve list create update].freeze
6
+ RESERVED = %i[retrieve list create update destroy].freeze
7
7
  ON_VALUES = %i[collection member].freeze
8
8
  ID_VALUES = %i[path param].freeze
9
9
  BUILT_IN = {
10
10
  retrieve: { method: :get, on: :member, path: nil, id: :path },
11
11
  list: { method: :get, on: :collection, path: nil },
12
12
  create: { method: :post, on: :collection, path: nil },
13
- update: { method: :put, on: :member, path: nil, id: :path }
13
+ update: { method: :put, on: :member, path: nil, id: :path },
14
+ destroy: { method: :delete, on: :member, path: nil, id: :path }
14
15
  }.freeze
15
16
 
16
17
  attr_reader :name, :owner, :on, :path, :id, :returns, :as
@@ -23,11 +24,18 @@ module Resteze
23
24
 
24
25
  validate_option_value!(name, options, :on, ON_VALUES)
25
26
  validate_option_value!(name, options, :id, ID_VALUES)
27
+ validate_path!(name, options[:path])
26
28
  return unless RESERVED.include?(name) && options.key?(:on)
27
29
 
28
30
  raise ArgumentError, "on: cannot be changed for the built-in action :#{name}"
29
31
  end
30
32
 
33
+ def self.validate_path!(name, path)
34
+ return unless path.to_s.split("/").any? { |segment| Resteze::Util.dot_segment?(segment) }
35
+
36
+ raise ArgumentError, "path: cannot contain a . or .. segment (action :#{name})"
37
+ end
38
+
31
39
  def self.validate_option_value!(name, options, key, values)
32
40
  return unless options.key?(key) && !values.include?(options[key])
33
41
 
@@ -81,11 +89,12 @@ module Resteze
81
89
  end
82
90
 
83
91
  def path_segments
84
- path.to_s.split("/").reject(&:blank?).map { |part| CGI.escape(part) }
92
+ path.to_s.split("/").reject(&:blank?).map { |part| Resteze::Util.encode_path_segment(part) }
85
93
  end
86
94
 
87
- def path_for(id = nil)
88
- base = member? && self.id == :path ? owner.resource_path(id) : owner.resource_path
95
+ # path_params fill the owner's path_template, when it declares one.
96
+ def path_for(id = nil, path_params = {})
97
+ base = member? && self.id == :path ? owner.resource_path(id, **path_params) : owner.resource_path(**path_params)
89
98
  [base, *path_segments].join("/").squeeze("/")
90
99
  end
91
100