whoosh 0.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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +18 -0
- data/LICENSE +21 -0
- data/README.md +209 -0
- data/lib/generators/whoosh/install/install_generator.rb +30 -0
- data/lib/generators/whoosh/install/templates/application_api.rb.tt +11 -0
- data/lib/generators/whoosh/install/templates/initializer.rb.tt +25 -0
- data/lib/generators/whoosh/install/templates/status_api.rb.tt +11 -0
- data/lib/generators/whoosh/install/templates/status_schema.rb.tt +4 -0
- data/lib/whoosh/api.rb +134 -0
- data/lib/whoosh/app.rb +280 -0
- data/lib/whoosh/configuration.rb +76 -0
- data/lib/whoosh/context.rb +56 -0
- data/lib/whoosh/endpoint.rb +168 -0
- data/lib/whoosh/errors.rb +62 -0
- data/lib/whoosh/idempotency.rb +70 -0
- data/lib/whoosh/json.rb +43 -0
- data/lib/whoosh/lazy_app.rb +28 -0
- data/lib/whoosh/openapi.rb +181 -0
- data/lib/whoosh/pagination.rb +109 -0
- data/lib/whoosh/railtie.rb +19 -0
- data/lib/whoosh/rate_limiter.rb +31 -0
- data/lib/whoosh/request.rb +120 -0
- data/lib/whoosh/router.rb +90 -0
- data/lib/whoosh/schema.rb +375 -0
- data/lib/whoosh/stores/cache.rb +40 -0
- data/lib/whoosh/stores/memory.rb +76 -0
- data/lib/whoosh/types.rb +153 -0
- data/lib/whoosh/version.rb +3 -0
- data/lib/whoosh.rb +72 -0
- metadata +92 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: ff849f212ecb40050dca2a2417944e173dfda1871cb4525c66421f3c13a09279
|
|
4
|
+
data.tar.gz: 42bc28f3813726695713969a6bc96c7afefc6d2b3d196bd5cffb04a0365f8944
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 5aba044d2fa3d10442c45e02f2a3ed4bad54a2bc734d17c43b78f91496f15dee454abc2fce69173eace72d4363d7318bf382465e71aa86afbd9f2cdf10428165
|
|
7
|
+
data.tar.gz: 8fb4f1652eda3f61cbff56155f4035796f77d3693a81059e330c8680468a647d4874e764987fe2d17861d3312ccf25d66cf31f66a191543f6bdcf7a8a052604c
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `Whoosh::API` classes are Rack apps: `run` standalone, or `mount` in Rails, Sinatra, Hanami
|
|
8
|
+
- Deny-by-default endpoints: each must declare `authorize` or `public!`, and `returns`, or definition fails
|
|
9
|
+
- `Whoosh::Schema` for input (coercion, validation, unknown keys dropped) and output (only declared fields serialized)
|
|
10
|
+
- One error envelope with request IDs; Active Record errors translated
|
|
11
|
+
- Limits on body size, JSON depth and key count, string length, array length and page size
|
|
12
|
+
- Per-endpoint rate limiting keyed by user or IP, including failed logins
|
|
13
|
+
- Idempotency keys with replay and reuse detection
|
|
14
|
+
- Cursor and offset pagination without COUNT(*)
|
|
15
|
+
- Closed-by-default CORS, security headers, HSTS over HTTPS
|
|
16
|
+
- OpenAPI 3.1 generation, optionally served at /openapi.json
|
|
17
|
+
- Memory and ActiveSupport::Cache stores; Rails Railtie and `whoosh:install` generator
|
|
18
|
+
- One runtime dependency: bigdecimal
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Johannes Dwi Cahyo Kristanto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# Whoosh
|
|
2
|
+
|
|
3
|
+
An opinionated, secure-by-default JSON API framework for Ruby. Run it on its own, or mount it inside Rails, Sinatra or Hanami and use your existing models.
|
|
4
|
+
|
|
5
|
+
```ruby
|
|
6
|
+
class OrdersApi < Whoosh::API
|
|
7
|
+
version 1
|
|
8
|
+
|
|
9
|
+
get "/orders" do
|
|
10
|
+
authorize { |user| user.staff? }
|
|
11
|
+
params { optional :status, :string, enum: Order.statuses.keys }
|
|
12
|
+
paginate
|
|
13
|
+
returns OrderSchema
|
|
14
|
+
handle { |p| current_user.store.orders.then { |o| p[:status] ? o.where(status: p[:status]) : o } }
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
post "/orders" do
|
|
18
|
+
authorize { |user| user.can_sell? }
|
|
19
|
+
idempotent
|
|
20
|
+
params do
|
|
21
|
+
required :customer_id, :integer
|
|
22
|
+
required :items, :array, max_items: 50 do
|
|
23
|
+
required :product_id, :integer
|
|
24
|
+
required :quantity, :integer, min: 1, max: 999
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
returns OrderSchema
|
|
28
|
+
handle { |p| Orders::Create.call(p, by: current_user) }
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## What "secure by default" means
|
|
34
|
+
|
|
35
|
+
An endpoint can't leak data, skip auth or accept unchecked input unless you write that down:
|
|
36
|
+
|
|
37
|
+
- **Deny by default.** Every endpoint must have `authorize { ... }` or `public!`, plus `returns` and `handle`. If one is missing, the class fails to load, so the app never boots with an open endpoint.
|
|
38
|
+
- **Declared input only.** Path, query and JSON body are merged and run through the `params` schema. Values are coerced and validated, and undeclared keys are dropped before the handler sees them, so mass assignment can't happen.
|
|
39
|
+
- **Declared output only.** Responses are serialized through the `returns` schema. A new `password_digest` column never ends up in JSON.
|
|
40
|
+
- **Limits everywhere:**
|
|
41
|
+
- 1 MB bodies
|
|
42
|
+
- JSON depth 20 and at most 1,000 keys
|
|
43
|
+
- strings capped at 10,000 characters
|
|
44
|
+
- arrays capped at 100 items
|
|
45
|
+
- at most 100 rows per page
|
|
46
|
+
- 300 requests per minute per user or IP, per endpoint
|
|
47
|
+
- **Rate limits apply before the 401 check**, so token guessing is throttled.
|
|
48
|
+
- **One error envelope** for every failure, with a request ID. In production a 500 never includes the exception message.
|
|
49
|
+
- **Locked-down headers:**
|
|
50
|
+
- CORS is closed until you list origins
|
|
51
|
+
- `nosniff`, `DENY` framing and `no-store` caching are on
|
|
52
|
+
- a restrictive CSP is set
|
|
53
|
+
- HSTS is sent over HTTPS
|
|
54
|
+
- **Idempotency keys** let unsafe endpoints like payments be retried safely.
|
|
55
|
+
|
|
56
|
+
## Why not Grape, or Rails with rack-attack, Pundit and a serializer?
|
|
57
|
+
|
|
58
|
+
Both work, and both are far more mature than Whoosh. The difference is what happens when someone forgets a step.
|
|
59
|
+
|
|
60
|
+
| | Rails + rack-attack + Pundit + serializer | Grape | Whoosh |
|
|
61
|
+
| --- | --- | --- | --- |
|
|
62
|
+
| Endpoint with no access rule | Works, unless you added `verify_authorized`, which fails at request time | Works | Class fails to load |
|
|
63
|
+
| Undeclared input | Dropped if you remember `permit` | Reaches the handler unless you call `declared(params)` | Always dropped |
|
|
64
|
+
| Undeclared output | Depends on the serializer you picked | Whatever you return, unless you use an entity | Never serialized |
|
|
65
|
+
| Rate limits, idempotency keys, pagination caps | Separate gems and your own code | Separate gems and your own code | Built in, on by default |
|
|
66
|
+
| OpenAPI | Separate gem, often written by hand | Separate gem | Generated from the same schemas |
|
|
67
|
+
|
|
68
|
+
Pick Grape or plain Rails if you need XML, file uploads, streaming or a large plugin ecosystem. Whoosh only does JSON, and it is new.
|
|
69
|
+
|
|
70
|
+
## Install
|
|
71
|
+
|
|
72
|
+
```ruby
|
|
73
|
+
gem "whoosh"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The only runtime dependency is `bigdecimal`, which Rails already pulls in. Whoosh speaks the Rack spec directly, and uses Oj for JSON when your app has it loaded.
|
|
77
|
+
|
|
78
|
+
### In Rails
|
|
79
|
+
|
|
80
|
+
```sh
|
|
81
|
+
bin/rails g whoosh:install
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
This creates `config/initializers/whoosh.rb`, `app/api/application_api.rb`, a status endpoint, and this route:
|
|
85
|
+
|
|
86
|
+
```ruby
|
|
87
|
+
# config/routes.rb
|
|
88
|
+
mount Whoosh.app("StatusApi", "OrdersApi"), at: "/api"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Pass class names as strings so development code reloading works. Handlers use your Active Record models, policies and service objects as usual. In Rails:
|
|
92
|
+
|
|
93
|
+
- `RecordNotFound` becomes a 404.
|
|
94
|
+
- `RecordInvalid` becomes a 422 with field errors.
|
|
95
|
+
- `RecordNotUnique` becomes a 409.
|
|
96
|
+
- Rate limits and idempotency keys are stored in `Rails.cache`, so they're shared across Puma workers.
|
|
97
|
+
|
|
98
|
+
### Standalone or Sinatra
|
|
99
|
+
|
|
100
|
+
```ruby
|
|
101
|
+
# config.ru
|
|
102
|
+
require "whoosh"
|
|
103
|
+
require_relative "api/orders_api"
|
|
104
|
+
run OrdersApi # or: run Whoosh.app(OrdersApi, CustomersApi)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
In Sinatra, `map("/api") { run OrdersApi }` in `config.ru`. See `examples/config.ru` for a complete app.
|
|
108
|
+
|
|
109
|
+
## Authentication
|
|
110
|
+
|
|
111
|
+
You provide one lambda that maps a request to a user (or `nil`):
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
Whoosh.configure do |config|
|
|
115
|
+
config.authenticate = lambda do |request|
|
|
116
|
+
token = request.bearer_token
|
|
117
|
+
token && ApiToken.active.find_by(digest: Digest::SHA256.hexdigest(token))&.user
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Store token digests, never raw tokens. `request.bearer_token` only accepts a well-formed `Authorization: Bearer ...` header.
|
|
123
|
+
|
|
124
|
+
## Endpoint DSL
|
|
125
|
+
|
|
126
|
+
| Method | Purpose |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `public!` | Anyone may call it. Otherwise a missing user gets 401. |
|
|
129
|
+
| `authorize { \|user, params\| ... }` | Falsey means 403. Runs after params are parsed. |
|
|
130
|
+
| `params { required/optional ... }` or `params SomeSchema` | Accepted input. Path params are added as strings if you don't declare them. |
|
|
131
|
+
| `returns Schema`, `returns Schema, many: true`, `returns nil` | Response shape. `nil` means 204. POST defaults to 201. |
|
|
132
|
+
| `returns { field ... }` | Inline response schema. |
|
|
133
|
+
| `paginate`, `paginate :cursor, by: :created_at, order: :desc`, `paginate :offset` | Adds `limit` plus `cursor` or `page`. Never runs `COUNT(*)`. |
|
|
134
|
+
| `idempotent`, `idempotent required: true` | Replays repeated `Idempotency-Key` requests. The same key with a different body gets 422. |
|
|
135
|
+
| `rate_limit 10, per: 60`, `rate_limit false` | Overrides the default limit. |
|
|
136
|
+
| `handle { \|params\| ... }` | Returns the object(s) to serialize. Returning `nil` for a single record gives 404. |
|
|
137
|
+
| `summary`, `description`, `tags`, `deprecated!` | OpenAPI docs. |
|
|
138
|
+
|
|
139
|
+
Inside `authorize` and `handle` you have `current_user`, `params`, `request`, your `helpers`, and:
|
|
140
|
+
|
|
141
|
+
```ruby
|
|
142
|
+
status 202
|
|
143
|
+
header "location", "/v1/orders/#{order.id}"
|
|
144
|
+
not_found! forbidden! conflict!("Already paid") bad_request!
|
|
145
|
+
invalid!(quantity: "is more than the stock left") # 422, field errors
|
|
146
|
+
error!(402, "payment_required", "Top up your balance first.")
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Class-level settings:
|
|
150
|
+
|
|
151
|
+
```ruby
|
|
152
|
+
class ApplicationApi < Whoosh::API
|
|
153
|
+
version 1 # /v1 prefix (declare before endpoints)
|
|
154
|
+
helpers { def current_store = current_user.store }
|
|
155
|
+
rescue_from(Xendit::Error) { |e| Whoosh::HTTPError.new(e.message, status: 502, code: "payment_gateway_error") }
|
|
156
|
+
openapi_info title: "Wicara API", version: "1.0.0"
|
|
157
|
+
end
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Schemas
|
|
161
|
+
|
|
162
|
+
```ruby
|
|
163
|
+
class OrderSchema < Whoosh::Schema
|
|
164
|
+
field :id, :integer
|
|
165
|
+
field :number, :string
|
|
166
|
+
field :total, :decimal # serialized as "125000.0", never a float
|
|
167
|
+
field :status, :string, enum: %w[pending paid cancelled]
|
|
168
|
+
field :placed_at, :datetime, from: :created_at
|
|
169
|
+
field :customer, CustomerSchema
|
|
170
|
+
field :items, :array, of: LineItemSchema, from: :line_items
|
|
171
|
+
field :store_name, :string, from: ->(order) { order.store.name }
|
|
172
|
+
end
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
- **Types:** `string text integer float decimal boolean date datetime time uuid email url array object json`.
|
|
176
|
+
- **Options:** `required default nullable enum min max min_length max_length min_items max_items format of from description example deprecated`.
|
|
177
|
+
- **Nesting:** pass a schema class, or a block (`field :address do ... end`).
|
|
178
|
+
- **Free-form data** needs `:json`. A bare `:object` without a schema is a definition error.
|
|
179
|
+
- **Strict input:** `reject_unknown!` makes unknown input keys a 422 instead of silently dropping them.
|
|
180
|
+
|
|
181
|
+
## Responses
|
|
182
|
+
|
|
183
|
+
```json
|
|
184
|
+
{ "data": { "id": 1, "number": "INV-1" } }
|
|
185
|
+
{ "data": [ ... ], "meta": { "limit": 25, "next_cursor": "WzI1XQ" } }
|
|
186
|
+
{ "error": { "code": "validation_failed", "message": "Some fields are invalid.",
|
|
187
|
+
"details": { "items[0].quantity": ["must be at least 1"] }, "request_id": "..." } }
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## OpenAPI
|
|
191
|
+
|
|
192
|
+
`OrdersApi.openapi` returns an OpenAPI 3.1 document built from the same schemas. Set `config.openapi = true` (or `:authenticated`) to serve it at `/openapi.json`. It's off by default.
|
|
193
|
+
|
|
194
|
+
## Performance
|
|
195
|
+
|
|
196
|
+
The full pipeline runs in about **30 µs** for a single record with auth, rate limiting, param validation and serialization, and about **140 µs** for 25 records, measured in-process on Ruby 3.3 (`rake bench`). Routes compile into a segment tree at boot. Schemas are plain Ruby objects with no per-request metaprogramming. JSON goes through Oj when available. In a real app, database time dominates.
|
|
197
|
+
|
|
198
|
+
## Development
|
|
199
|
+
|
|
200
|
+
```sh
|
|
201
|
+
bundle install
|
|
202
|
+
bundle exec rake test
|
|
203
|
+
bundle exec rake bench
|
|
204
|
+
bundle exec rackup examples/config.ru
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## License
|
|
208
|
+
|
|
209
|
+
MIT
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
require "rails/generators"
|
|
2
|
+
|
|
3
|
+
module Whoosh
|
|
4
|
+
module Generators
|
|
5
|
+
# bin/rails g whoosh:install [--path=/api]
|
|
6
|
+
class InstallGenerator < Rails::Generators::Base
|
|
7
|
+
source_root File.expand_path("templates", __dir__)
|
|
8
|
+
class_option :path, type: :string, default: "/api", desc: "Where to mount the API"
|
|
9
|
+
|
|
10
|
+
def create_files
|
|
11
|
+
template "initializer.rb.tt", "config/initializers/whoosh.rb"
|
|
12
|
+
template "application_api.rb.tt", "app/api/application_api.rb"
|
|
13
|
+
template "status_api.rb.tt", "app/api/status_api.rb"
|
|
14
|
+
template "status_schema.rb.tt", "app/schemas/status_schema.rb"
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def mount
|
|
18
|
+
route %(mount Whoosh.app("StatusApi"), at: "#{options[:path]}")
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def next_steps
|
|
22
|
+
say ""
|
|
23
|
+
say "Whoosh is installed.", :green
|
|
24
|
+
say " 1. Set config.authenticate in config/initializers/whoosh.rb"
|
|
25
|
+
say " 2. curl localhost:3000#{options[:path]}/v1/status"
|
|
26
|
+
say " 3. Add API classes in app/api/ and list them in the mount line in config/routes.rb"
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Base class for your APIs: shared version, helpers and error mapping.
|
|
2
|
+
class ApplicationApi < Whoosh::API
|
|
3
|
+
version 1
|
|
4
|
+
|
|
5
|
+
helpers do
|
|
6
|
+
# Available in every authorize/handle block.
|
|
7
|
+
# def current_store = current_user.store
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
# rescue_from(Payment::Declined) { |e| Whoosh::HTTPError.new(e.message, status: 402, code: "payment_declined") }
|
|
11
|
+
end
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Whoosh.configure do |config|
|
|
2
|
+
# Who is calling? Return the user, or nil. Endpoints that aren't `public!`
|
|
3
|
+
# answer 401 for nil. Example with a hashed API token column:
|
|
4
|
+
#
|
|
5
|
+
# config.authenticate = lambda do |request|
|
|
6
|
+
# token = request.bearer_token
|
|
7
|
+
# token && ApiToken.active.find_by(digest: Digest::SHA256.hexdigest(token))&.user
|
|
8
|
+
# end
|
|
9
|
+
#
|
|
10
|
+
# Or reuse the Rails session cookie (same-site browser clients):
|
|
11
|
+
# config.authenticate = ->(request) { Session.find_by(id: request.env["rack.session"]&.dig("session_id"))&.user }
|
|
12
|
+
config.authenticate = ->(_request) { nil }
|
|
13
|
+
|
|
14
|
+
# Browser origins allowed to call the API. Empty = no cross-origin access.
|
|
15
|
+
# config.cors_origins = ["https://app.example.com"]
|
|
16
|
+
|
|
17
|
+
# Default limit per client per endpoint. Override per endpoint with `rate_limit`.
|
|
18
|
+
# config.rate_limit = [300, 60]
|
|
19
|
+
|
|
20
|
+
# Serve /openapi.json. true, :authenticated, or false.
|
|
21
|
+
config.openapi = Rails.env.development? ? true : false
|
|
22
|
+
|
|
23
|
+
# Report unexpected errors.
|
|
24
|
+
# config.on_error = ->(error, request) { Sentry.capture_exception(error, extra: { request_id: request.request_id }) }
|
|
25
|
+
end
|
data/lib/whoosh/api.rb
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# Subclass to define endpoints. Each subclass is a Rack app.
|
|
3
|
+
#
|
|
4
|
+
# class ApplicationAPI < Whoosh::API
|
|
5
|
+
# version 1
|
|
6
|
+
# helpers do
|
|
7
|
+
# def current_store = current_user.store
|
|
8
|
+
# end
|
|
9
|
+
# end
|
|
10
|
+
#
|
|
11
|
+
# class OrdersAPI < ApplicationAPI
|
|
12
|
+
# get "/orders" do
|
|
13
|
+
# authorize { |user| user.staff? }
|
|
14
|
+
# paginate
|
|
15
|
+
# returns OrderSchema
|
|
16
|
+
# handle { current_store.orders }
|
|
17
|
+
# end
|
|
18
|
+
# end
|
|
19
|
+
class API
|
|
20
|
+
class << self
|
|
21
|
+
def inherited(subclass)
|
|
22
|
+
super
|
|
23
|
+
subclass.instance_variable_set(:@path_prefix, path_prefix)
|
|
24
|
+
subclass.instance_variable_set(:@helper_modules, helper_modules.dup)
|
|
25
|
+
subclass.instance_variable_set(:@rescue_handlers, rescue_handlers.dup)
|
|
26
|
+
subclass.instance_variable_set(:@default_tags, default_tags.dup)
|
|
27
|
+
subclass.instance_variable_set(:@info, info.dup)
|
|
28
|
+
subclass.instance_variable_set(:@endpoints, [])
|
|
29
|
+
subclass.instance_variable_set(:@definition_router, nil)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Prefixes every path with /v<n>. Declare before any endpoint.
|
|
33
|
+
def version(number)
|
|
34
|
+
set_prefix("#{path_prefix}/v#{Integer(number)}")
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Prefixes every path. Declare before any endpoint.
|
|
38
|
+
def prefix(path)
|
|
39
|
+
set_prefix("#{path_prefix}/#{path.to_s.delete_prefix('/').chomp('/')}")
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def path_prefix = @path_prefix || ""
|
|
43
|
+
|
|
44
|
+
# Methods available inside authorize and handle blocks.
|
|
45
|
+
# helpers do
|
|
46
|
+
# def current_store = current_user.store
|
|
47
|
+
# end
|
|
48
|
+
# helpers StoreHelpers
|
|
49
|
+
def helpers(mod = nil, &block)
|
|
50
|
+
helper_modules << mod if mod
|
|
51
|
+
helper_modules << Module.new(&block) if block
|
|
52
|
+
@context_class = nil
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def helper_modules = (@helper_modules ||= [])
|
|
56
|
+
|
|
57
|
+
# Map your own exceptions to responses. Return a Whoosh::HTTPError.
|
|
58
|
+
# rescue_from(Xendit::CardDeclined) { |e| Whoosh::HTTPError.new(e.message, status: 402, code: "card_declined") }
|
|
59
|
+
def rescue_from(*classes, &block)
|
|
60
|
+
raise DefinitionError, "rescue_from needs a block" unless block
|
|
61
|
+
|
|
62
|
+
classes.each { |klass| rescue_handlers << [klass, block] }
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def rescue_handlers = (@rescue_handlers ||= [])
|
|
66
|
+
|
|
67
|
+
# Default OpenAPI tag for this class's endpoints.
|
|
68
|
+
def tag(*names)
|
|
69
|
+
@default_tags = names.flatten.map(&:to_s)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def default_tags = (@default_tags ||= [])
|
|
73
|
+
|
|
74
|
+
# Title, version and description for the OpenAPI document.
|
|
75
|
+
def openapi_info(**values)
|
|
76
|
+
info.merge!(values.transform_keys(&:to_s))
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def info = (@info ||= {})
|
|
80
|
+
|
|
81
|
+
Endpoint::VERBS.each do |verb|
|
|
82
|
+
define_method(verb.downcase) do |path, &block|
|
|
83
|
+
define_endpoint(verb, path, &block)
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def endpoints = (@endpoints ||= [])
|
|
88
|
+
|
|
89
|
+
def context_class
|
|
90
|
+
@context_class ||= begin
|
|
91
|
+
modules = helper_modules
|
|
92
|
+
Class.new(Context) { modules.each { |m| include m } }
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# The Rack interface: `run OrdersAPI` or `mount OrdersAPI => "/api"`.
|
|
97
|
+
def call(env)
|
|
98
|
+
(@app ||= App.new([self])).call(env)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def routes
|
|
102
|
+
endpoints.map { |ep| [ep.verb, ep.path] }
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def openapi(**options)
|
|
106
|
+
OpenAPI.new([self], **options).document
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
private
|
|
110
|
+
|
|
111
|
+
def set_prefix(value)
|
|
112
|
+
raise DefinitionError, "#{name}: declare version/prefix before any endpoint" if endpoints.any?
|
|
113
|
+
|
|
114
|
+
@path_prefix = value
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def define_endpoint(verb, path, &block)
|
|
118
|
+
raise DefinitionError, "#{name} #{verb} #{path}: endpoints need a block" unless block
|
|
119
|
+
|
|
120
|
+
full = "#{path_prefix}/#{path.to_s.delete_prefix('/')}".chomp("/")
|
|
121
|
+
full = "/" if full.empty?
|
|
122
|
+
endpoint = Endpoint.new(self, verb, full)
|
|
123
|
+
endpoint.instance_eval(&block)
|
|
124
|
+
endpoint.tags(*default_tags) if endpoint.docs[:tags].nil? && default_tags.any?
|
|
125
|
+
endpoint.finalize!
|
|
126
|
+
# Fails now (at boot) on duplicate routes or conflicting param names.
|
|
127
|
+
(@definition_router ||= Router.new).add(verb, full, endpoint)
|
|
128
|
+
endpoints << endpoint
|
|
129
|
+
@app = nil
|
|
130
|
+
endpoint
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
end
|