media_types-serialization 0.8.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.
- checksums.yaml +4 -4
- data/.github/workflows/ci.yml +16 -3
- data/.prettierrc +1 -0
- data/CHANGELOG.md +42 -0
- data/CODE_OF_CONDUCT.md +74 -74
- data/Gemfile.lock +74 -83
- data/README.md +691 -179
- data/lib/media_types/problem.rb +64 -0
- data/lib/media_types/serialization.rb +497 -173
- data/lib/media_types/serialization/base.rb +115 -91
- data/lib/media_types/serialization/error.rb +186 -0
- data/lib/media_types/serialization/fake_validator.rb +52 -0
- data/lib/media_types/serialization/serialization_dsl.rb +117 -0
- data/lib/media_types/serialization/serialization_registration.rb +245 -0
- data/lib/media_types/serialization/serializers/api_viewer.rb +133 -0
- data/lib/media_types/serialization/serializers/common_css.rb +168 -0
- data/lib/media_types/serialization/serializers/endpoint_description_serializer.rb +80 -0
- data/lib/media_types/serialization/serializers/fallback_not_acceptable_serializer.rb +85 -0
- data/lib/media_types/serialization/serializers/fallback_unsupported_media_type_serializer.rb +58 -0
- data/lib/media_types/serialization/serializers/input_validation_error_serializer.rb +89 -0
- data/lib/media_types/serialization/serializers/problem_serializer.rb +100 -0
- data/lib/media_types/serialization/utils/accept_header.rb +77 -0
- data/lib/media_types/serialization/utils/accept_language_header.rb +82 -0
- data/lib/media_types/serialization/utils/header_list.rb +89 -0
- data/lib/media_types/serialization/version.rb +1 -1
- data/media_types-serialization.gemspec +48 -50
- metadata +48 -79
- data/.travis.yml +0 -17
- data/lib/generators/media_types/serialization/api_viewer/api_viewer_generator.rb +0 -25
- data/lib/generators/media_types/serialization/api_viewer/templates/api_viewer.html.erb +0 -98
- data/lib/generators/media_types/serialization/api_viewer/templates/initializer.rb +0 -33
- data/lib/generators/media_types/serialization/api_viewer/templates/template_controller.rb +0 -23
- data/lib/media_types/serialization/media_type/register.rb +0 -4
- data/lib/media_types/serialization/migrations_command.rb +0 -38
- data/lib/media_types/serialization/migrations_support.rb +0 -50
- data/lib/media_types/serialization/mime_type_support.rb +0 -64
- data/lib/media_types/serialization/no_content_type_given.rb +0 -11
- data/lib/media_types/serialization/no_media_type_serializers.rb +0 -11
- data/lib/media_types/serialization/no_serializer_for_content_type.rb +0 -15
- data/lib/media_types/serialization/renderer.rb +0 -41
- data/lib/media_types/serialization/renderer/register.rb +0 -4
- data/lib/media_types/serialization/wrapper.rb +0 -13
- data/lib/media_types/serialization/wrapper/html_wrapper.rb +0 -45
- data/lib/media_types/serialization/wrapper/media_collection_wrapper.rb +0 -59
- data/lib/media_types/serialization/wrapper/media_index_wrapper.rb +0 -59
- data/lib/media_types/serialization/wrapper/media_object_wrapper.rb +0 -55
- data/lib/media_types/serialization/wrapper_support.rb +0 -38
data/README.md
CHANGED
@@ -4,7 +4,7 @@
|
|
4
4
|
[](https://badge.fury.io/rb/media_types-serialization)
|
5
5
|
[](http://opensource.org/licenses/MIT)
|
6
6
|
|
7
|
-
Add
|
7
|
+
`respond_to` on steroids. Add [HATEOAS](https://docs.delftsolutions.nl/wiki/HATEOAS_API) compatible serialization and deserialization to your Rails projects.
|
8
8
|
|
9
9
|
## Installation
|
10
10
|
|
@@ -21,275 +21,787 @@ And then execute:
|
|
21
21
|
Or install it yourself as:
|
22
22
|
|
23
23
|
$ gem install media_types-serialization
|
24
|
-
|
25
|
-
If you have not done this before, and you're using `rails`, install the necessary parts using:
|
26
24
|
|
27
|
-
|
28
|
-
|
25
|
+
## Usage
|
26
|
+
|
27
|
+
Serializers help you in converting a ruby object to a representation matching a specified [Media Type validator](https://github.com/SleeplessByte/media-types-ruby) and the other way around.
|
28
|
+
|
29
|
+
### Creating a serializer
|
30
|
+
|
31
|
+
```ruby
|
32
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
33
|
+
unvalidated 'application/vnd.acme.book'
|
34
|
+
|
35
|
+
# outputs with a Content-Type of application/vnd.acme.book.v1+json
|
36
|
+
output version: 1 do |obj, version, context|
|
37
|
+
{
|
38
|
+
book: {
|
39
|
+
title: obj.title
|
40
|
+
}
|
41
|
+
}
|
42
|
+
end
|
43
|
+
end
|
29
44
|
```
|
30
45
|
|
31
|
-
|
46
|
+
To convert a ruby object to a json representation:
|
32
47
|
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
|
48
|
+
```ruby
|
49
|
+
class Book
|
50
|
+
attr_accessor :title
|
51
|
+
end
|
37
52
|
|
38
|
-
|
53
|
+
book = Book.new
|
54
|
+
book.title = 'Everything, abridged'
|
55
|
+
|
56
|
+
BookSerializer.serialize(book, 'vnd.acme.book.v1+json', context: nil)
|
57
|
+
# => { "book": { "title": "Everything, abridged" } }
|
58
|
+
```
|
39
59
|
|
40
|
-
|
60
|
+
### Controller integration
|
41
61
|
|
42
|
-
|
62
|
+
You can integrate the serialization system in rails, giving you automatic [Content-Type negotiation](https://en.wikipedia.org/wiki/Content_negotiation) using the `Accept` header:
|
43
63
|
|
44
|
-
Add a serializer that can serialize a certain media type. The `to_hash` function will be called _explicitly_ in your
|
45
|
-
controller, so you can always use your own, favourite serializer here to do the hefty work. This gem does provide some
|
46
|
-
easy tools, usually enough to do most serialization.
|
47
|
-
|
48
64
|
```ruby
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
|
58
|
-
|
59
|
-
|
65
|
+
require 'media_types/serialization'
|
66
|
+
|
67
|
+
class BookController < ActionController::API
|
68
|
+
include MediaTypes::Serialization
|
69
|
+
|
70
|
+
allow_output_serializer(BookSerializer, only: %i[show])
|
71
|
+
freeze_io!
|
72
|
+
|
73
|
+
def show
|
74
|
+
book = Book.new
|
75
|
+
book.title = 'Everything, abridged'
|
76
|
+
|
77
|
+
render_media book
|
78
|
+
end
|
79
|
+
end
|
80
|
+
```
|
81
|
+
|
82
|
+
While using the controller integration the context will always be set to the current controller. This allows you to construct urls.
|
83
|
+
|
84
|
+
### Adding HATEOAS responses to existing routes
|
85
|
+
|
86
|
+
When creating a mobile application it's often useful to allow the app to request a non-html representation of a specific url. If you have an existing route:
|
87
|
+
|
88
|
+
```ruby
|
89
|
+
class BookController < ApplicationController
|
90
|
+
def show
|
91
|
+
@book = Book.new
|
92
|
+
|
93
|
+
# Use view corresponding to the controller
|
94
|
+
end
|
95
|
+
end
|
96
|
+
```
|
97
|
+
|
98
|
+
You can add a json representation as follows:
|
99
|
+
|
100
|
+
```ruby
|
101
|
+
class BookController < ApplicationController
|
102
|
+
allow_output_serializer(BookSerializer, only: %i[show])
|
103
|
+
allow_output_html
|
104
|
+
freeze_io!
|
105
|
+
|
106
|
+
def show
|
107
|
+
@book = Book.new
|
60
108
|
|
61
|
-
|
62
|
-
|
63
|
-
|
109
|
+
render_media @book
|
110
|
+
end
|
111
|
+
end
|
112
|
+
```
|
113
|
+
|
114
|
+
### Validations
|
115
|
+
|
116
|
+
Right now the serializer does not validate incoming or outgoing information. This can cause issues when you accidentally emit non-conforming data that people start to depend on. To make sure you don't do that you can specify a [Media Type validator](https://github.com/SleeplessByte/media-types-ruby):
|
117
|
+
|
118
|
+
```ruby
|
119
|
+
require 'media_types'
|
120
|
+
|
121
|
+
class BookValidator
|
122
|
+
include MediaTypes::Dsl
|
123
|
+
|
124
|
+
def self.organisation
|
125
|
+
'acme'
|
126
|
+
end
|
127
|
+
|
128
|
+
use_name 'book'
|
129
|
+
|
130
|
+
validations do
|
131
|
+
version 1 do
|
132
|
+
attribute :book do
|
133
|
+
attribute :title, String
|
64
134
|
end
|
65
135
|
end
|
136
|
+
end
|
137
|
+
end
|
66
138
|
|
67
|
-
|
68
|
-
|
69
|
-
protected
|
70
|
-
|
71
|
-
def extract_self
|
72
|
-
# A serializer gets the controller as context
|
73
|
-
{ href: context.api_book_url(serializable) }
|
74
|
-
end
|
139
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
140
|
+
validator BookValidator
|
75
141
|
|
76
|
-
|
77
|
-
|
78
|
-
|
79
|
-
|
142
|
+
# outputs with a Content-Type of application/vnd.acme.book.v1+json
|
143
|
+
output version: 1 do |obj, version, context|
|
144
|
+
{
|
145
|
+
book: {
|
146
|
+
title: obj.title
|
80
147
|
}
|
148
|
+
}
|
149
|
+
end
|
150
|
+
end
|
151
|
+
```
|
152
|
+
|
153
|
+
For more information, see the [Media Types docs](https://github.com/SleeplessByte/media-types-ruby).
|
154
|
+
|
155
|
+
### Versioning
|
156
|
+
|
157
|
+
To help with supporting older versions, serializers have a [DSL](https://en.wikipedia.org/wiki/Domain-specific_language) to construct json objects:
|
158
|
+
|
159
|
+
```ruby
|
160
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
161
|
+
validator BookValidator
|
162
|
+
|
163
|
+
output versions: [1, 2] do |obj, version, context|
|
164
|
+
attribute :book do
|
165
|
+
attribute :title, obj.title
|
166
|
+
attribute :description, obj.description if version >= 2
|
81
167
|
end
|
82
168
|
end
|
83
169
|
end
|
84
170
|
```
|
85
|
-
By default, The passed in `MediaType` gets converted into a constructable (via `to_constructable`) and invoked with the
|
86
|
-
current `view` (e.g. `create`, `index`, `collection` or ` `). This means that by default it will be able to serialize
|
87
|
-
the latest version you `MediaType` is reporting. The best way to supply your media type is via the [`media_types`](https://github.com/SleeplessByte/media-types-ruby) gem.
|
88
171
|
|
89
|
-
|
172
|
+
```ruby
|
173
|
+
BookSerializer.serialize(book, BookValidator.version(1), context: nil)
|
174
|
+
# => { "book": { "title": "Everything, abridged" } }
|
175
|
+
|
176
|
+
BookSerializer.serialize(book, BookValidator.version(2), context: nil)
|
177
|
+
# => { "book": { "title": "Everything, abridged", "description": "Mu" } }
|
178
|
+
```
|
179
|
+
|
180
|
+
### Links
|
90
181
|
|
91
|
-
|
92
|
-
- suffix `+json` if you define `to_json`
|
93
|
-
- suffix `+xml` if you define `to_xml`
|
94
|
-
- type `text/html` if you define `to_html`
|
182
|
+
When making [HATEOAS](https://docs.delftsolutions.nl/wiki/HATEOAS_API) compliant applications it's very useful to include `Link` headers in your response so clients can use a `HEAD` request instead of having to fetch the entire resource. Serializers have convenience methods to help with this:
|
95
183
|
|
96
|
-
|
97
|
-
|
184
|
+
```ruby
|
185
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
186
|
+
validator BookValidator
|
98
187
|
|
99
|
-
|
100
|
-
|
188
|
+
output versions: [1, 2, 3] do |obj, version, context|
|
189
|
+
attribute :book do
|
190
|
+
link :self, href: context.book_url(obj) if version >= 3
|
101
191
|
|
102
|
-
|
192
|
+
attribute :title, obj.title
|
193
|
+
attribute :description, obj.description if version >= 2
|
194
|
+
end
|
195
|
+
end
|
196
|
+
end
|
197
|
+
```
|
103
198
|
|
104
|
-
|
105
|
-
handle this is via backward migrations, meaning you'll migrate from the current version back to an older version.
|
199
|
+
This returns the following response:
|
106
200
|
|
107
201
|
```ruby
|
108
|
-
|
109
|
-
|
110
|
-
|
111
|
-
|
112
|
-
|
113
|
-
|
114
|
-
|
115
|
-
|
116
|
-
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
|
202
|
+
BookSerializer.serialize(book, BookValidator.version(3), context: controller)
|
203
|
+
# header = Link: <https://example.org/>; rel="self"
|
204
|
+
# => {
|
205
|
+
# "book": {
|
206
|
+
# "_links": {
|
207
|
+
# "self": { "href": "https://example.org" }
|
208
|
+
# },
|
209
|
+
# "title": "Everything, abridged",
|
210
|
+
# "description": "Mu"
|
211
|
+
# }
|
212
|
+
# }
|
213
|
+
```
|
214
|
+
|
215
|
+
### Collections
|
216
|
+
|
217
|
+
There are convenience methods for serializing arrays of objects based on a template.
|
218
|
+
|
219
|
+
#### Indexes
|
220
|
+
|
221
|
+
An index is a collection of urls that point to members of the array. The index method automatically generates it based on the self links defined in the default view of the same version.
|
222
|
+
|
223
|
+
```ruby
|
224
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
225
|
+
validator BookValidator
|
226
|
+
|
227
|
+
output versions: [1, 2, 3] do |obj, version, context|
|
228
|
+
attribute :book do
|
229
|
+
link :self, href: context.book_url(obj) if version >= 3
|
230
|
+
|
231
|
+
attribute :title, obj.title
|
232
|
+
attribute :description, obj.description if version >= 2
|
124
233
|
end
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
version 1 do |result|
|
133
|
-
result.tap do |r|
|
134
|
-
if r.key?(:views)
|
135
|
-
r[:views_count] = r.delete(:views)
|
136
|
-
end
|
137
|
-
end
|
138
|
-
end
|
234
|
+
end
|
235
|
+
|
236
|
+
output view: :index, version: 3 do |arr, version, context|
|
237
|
+
attribute :books do
|
238
|
+
link :self, href: context.book_index_url
|
239
|
+
|
240
|
+
index arr, version: version
|
139
241
|
end
|
140
242
|
end
|
141
243
|
end
|
142
244
|
```
|
143
245
|
|
144
|
-
|
246
|
+
```ruby
|
247
|
+
BookSerializer.serialize([book], BookValidator.view(:index).version(3), context: controller)
|
248
|
+
# header = Link: <https://example.org/index>; rel="self"
|
249
|
+
# => {
|
250
|
+
# "books": {
|
251
|
+
# "_links": {
|
252
|
+
# "self": { "href": "https://example.org" }
|
253
|
+
# },
|
254
|
+
# "_index": [
|
255
|
+
# { "href": "https://example.org" }
|
256
|
+
# ]
|
257
|
+
# }
|
258
|
+
# }
|
259
|
+
```
|
260
|
+
|
261
|
+
#### Collections
|
145
262
|
|
146
|
-
|
147
|
-
uses the serialization, you need to explicitly `accept` it if you want to use the built-in lookups.
|
263
|
+
A collection inlines the member objects. The collection method automatically generates it based on the default view of the same version.
|
148
264
|
|
149
265
|
```ruby
|
150
|
-
|
151
|
-
|
266
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
267
|
+
validator BookValidator
|
152
268
|
|
153
|
-
|
154
|
-
|
269
|
+
output versions: [1, 2, 3] do |obj, version, context|
|
270
|
+
attribute :book do
|
271
|
+
link :self, href: context.book_url(obj) if version >= 3
|
272
|
+
|
273
|
+
attribute :title, obj.title
|
274
|
+
attribute :description, obj.description if version >= 2
|
275
|
+
end
|
276
|
+
end
|
277
|
+
|
278
|
+
output view: :index, version: 3 do |arr, version, context|
|
279
|
+
attribute :books do
|
280
|
+
link :self, href: context.book_index_url
|
281
|
+
|
282
|
+
index arr, version: version
|
283
|
+
end
|
284
|
+
end
|
285
|
+
|
286
|
+
output view: :collection, version: 3 do |arr, version, context|
|
287
|
+
attribute :books do
|
288
|
+
link :self, href: context.book_collection_url
|
289
|
+
|
290
|
+
collection arr, version: version
|
291
|
+
end
|
292
|
+
end
|
293
|
+
end
|
294
|
+
```
|
295
|
+
|
296
|
+
```ruby
|
297
|
+
BookSerializer.serialize([book], BookValidator.view(:collection).version(3), context: controller)
|
298
|
+
# header = Link: <https://example.org/collection>; rel="self"
|
299
|
+
# => {
|
300
|
+
# "books": {
|
301
|
+
# "_links": {
|
302
|
+
# "self": { "href": "https://example.org" }
|
303
|
+
# },
|
304
|
+
# "_embedded": [
|
305
|
+
# {
|
306
|
+
# "_links": {
|
307
|
+
# "self": { "href": "https://example.org" }
|
308
|
+
# },
|
309
|
+
# "title": "Everything, abridged",
|
310
|
+
# "description": "Mu"
|
311
|
+
# }
|
312
|
+
# ]
|
313
|
+
# }
|
314
|
+
# }
|
315
|
+
```
|
316
|
+
|
317
|
+
### Input deserialization
|
318
|
+
|
319
|
+
You can mark a media type as something that's allowed to be sent along with a PUT request as follows:
|
320
|
+
|
321
|
+
```ruby
|
322
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
323
|
+
validator BookValidator
|
324
|
+
|
325
|
+
output versions: [1, 2, 3] do |obj, version, context|
|
326
|
+
attribute :book do
|
327
|
+
link :self, href: context.book_url(obj) if version >= 3
|
328
|
+
|
329
|
+
attribute :title, obj.title
|
330
|
+
attribute :description, obj.description if version >= 2
|
331
|
+
end
|
332
|
+
|
333
|
+
input version: 3
|
155
334
|
end
|
156
335
|
|
157
|
-
class BookController <
|
158
|
-
|
159
|
-
|
160
|
-
|
161
|
-
|
162
|
-
|
163
|
-
|
164
|
-
|
165
|
-
|
166
|
-
|
167
|
-
|
168
|
-
render media: serialize_media(
|
336
|
+
class BookController < ActionController::API
|
337
|
+
include MediaTypes::Serialization
|
338
|
+
|
339
|
+
allow_output_serializer(BookSerializer, only: %i[show])
|
340
|
+
allow_input_serializer(BookSerializer, only: %i[create])
|
341
|
+
freeze_io!
|
342
|
+
|
343
|
+
def show
|
344
|
+
book = Book.new
|
345
|
+
book.title = 'Everything, abridged'
|
346
|
+
|
347
|
+
render media: serialize_media(book), content_type: request.format.to_s
|
348
|
+
end
|
349
|
+
|
350
|
+
def create
|
351
|
+
json = deserialize(request, context: self) # does validation for us
|
352
|
+
puts json
|
169
353
|
end
|
170
354
|
end
|
171
355
|
```
|
172
356
|
|
173
|
-
If you
|
174
|
-
`BaseController` and render resources like so:
|
357
|
+
If you use [ActiveRecord](https://guides.rubyonrails.org/active_record_basics.html) you might want to convert the verified json data during deserialization:
|
175
358
|
|
176
359
|
```ruby
|
177
|
-
class
|
178
|
-
|
179
|
-
|
360
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
361
|
+
validator BookValidator
|
362
|
+
|
363
|
+
output versions: [1, 2, 3] do |obj, version, context|
|
364
|
+
attribute :book do
|
365
|
+
link :self, href: context.book_url(obj) if version >= 3
|
366
|
+
|
367
|
+
attribute :title, obj.title
|
368
|
+
attribute :description, obj.description if version >= 2
|
369
|
+
end
|
370
|
+
|
371
|
+
input versions: [1, 2, 3] do |json, version, context|
|
372
|
+
book = Book.new
|
373
|
+
book.title = json['book']['title']
|
374
|
+
book.description = 'Not available'
|
375
|
+
book.description = json['book']['description'] if version >= 2
|
376
|
+
|
377
|
+
# Best practise is to only save in the controller.
|
378
|
+
book
|
379
|
+
end
|
380
|
+
end
|
381
|
+
|
382
|
+
class BookController < ActionController::API
|
383
|
+
include MediaTypes::Serialization
|
384
|
+
|
385
|
+
allow_output_serializer(BookSerializer, only: %i[show])
|
386
|
+
allow_input_serializer(BookSerializer, only: %i[create])
|
387
|
+
freeze_io!
|
388
|
+
|
389
|
+
def show
|
390
|
+
book = Book.new
|
391
|
+
book.title = 'Everything, abridged'
|
392
|
+
|
393
|
+
render media: serialize_media(book), content_type: request.format.to_s
|
394
|
+
end
|
395
|
+
|
396
|
+
def create
|
397
|
+
book = deserialize(request, context: self)
|
398
|
+
book.save!
|
399
|
+
|
400
|
+
render media: serialize_media(book), content_type request.format.to_s
|
180
401
|
end
|
181
402
|
end
|
182
403
|
```
|
183
404
|
|
184
|
-
|
405
|
+
If you don't want to apply any input validation or deserialization you can use the `allow_all_input` method instead of `allow_input_serialization`.
|
185
406
|
|
186
|
-
###
|
407
|
+
### Raw output
|
187
408
|
|
188
|
-
|
189
|
-
only be one (1) active `text/html` serializer for each action; a single controller can have multiple registered, but
|
190
|
-
never for the same preconditions in `before_action` (because how else would it know which one to pick?).
|
409
|
+
Sometimes you need to output raw data. This cannot be validated. You do this as follows:
|
191
410
|
|
192
|
-
Use the `render` method to generate your HTML:
|
193
411
|
```ruby
|
194
|
-
class
|
195
|
-
|
196
|
-
|
197
|
-
|
198
|
-
|
199
|
-
|
200
|
-
|
201
|
-
|
202
|
-
|
203
|
-
|
204
|
-
|
205
|
-
language_links: language_links,
|
206
|
-
},
|
207
|
-
layout: false
|
208
|
-
)
|
412
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
413
|
+
validator BookValidator
|
414
|
+
|
415
|
+
output_raw view: :raw, version: 3 do |obj, version, context|
|
416
|
+
hidden do
|
417
|
+
# Make sure links are only set in the headers, not in the body.
|
418
|
+
|
419
|
+
link :self, href: context.book_url(obj)
|
420
|
+
end
|
421
|
+
|
422
|
+
"I'm a non-json output"
|
209
423
|
end
|
210
|
-
|
211
|
-
# Naturally you have to define extract_title, etc etc
|
212
424
|
end
|
213
425
|
```
|
214
426
|
|
215
|
-
|
427
|
+
### Raw input
|
428
|
+
|
429
|
+
You can do the same with input:
|
216
430
|
|
217
431
|
```ruby
|
218
|
-
|
432
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
433
|
+
validator BookValidator
|
434
|
+
|
435
|
+
input_raw view: raw, version: 3 do |bytes, version, context|
|
436
|
+
book = Book.new
|
437
|
+
book.description = bytes
|
438
|
+
|
439
|
+
book
|
440
|
+
end
|
441
|
+
end
|
219
442
|
```
|
220
443
|
|
221
|
-
###
|
444
|
+
### Remapping media type identifiers
|
222
445
|
|
223
|
-
|
224
|
-
using `rails` you'll want to register it. You can do so manually, or by `require`ing:
|
446
|
+
Sometimes you already have old clients using an `application/json` media type identifier when they do requests. While this is not a good practise as this makes it hard to add new fields or remove old ones, this library has support for migrating away:
|
225
447
|
|
226
448
|
```ruby
|
227
|
-
|
449
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
450
|
+
validator BookValidator
|
451
|
+
|
452
|
+
output versions: [1, 2, 3] do |obj, version, context|
|
453
|
+
attribute :book do
|
454
|
+
link :self, href: context.book_url(obj) if version >= 3
|
455
|
+
|
456
|
+
attribute :title, obj.title
|
457
|
+
attribute :description, obj.description if version >= 2
|
458
|
+
end
|
459
|
+
end
|
460
|
+
output_alias 'application/json' # maps application/json to to applicaton/vnd.acme.book.v1+json
|
461
|
+
|
462
|
+
input view: :create, versions: [1, 2, 3] do |json, version, context|
|
463
|
+
book = Book.new
|
464
|
+
book.title = json['book']['title']
|
465
|
+
book.description = 'Not available'
|
466
|
+
book.description = json['book']['description'] if version >= 2
|
467
|
+
|
468
|
+
# Make sure not to save here but only save in the controller
|
469
|
+
book
|
470
|
+
end
|
471
|
+
input_alias 'application/json', view: :create # maps application/json to to applicaton/vnd.acme.book.v1+json
|
228
472
|
```
|
229
473
|
|
230
|
-
|
474
|
+
Validation will be done using the remapped validator. Aliasses map to version `nil` if that is available or `1` otherwise. It is not possible to configure this version.
|
231
475
|
|
232
|
-
|
476
|
+
### HTML
|
477
|
+
|
478
|
+
This library has a built in API viewer. The viewer can be accessed by by appending a `?api_viewer=last` query parameter to the URL.
|
479
|
+
|
480
|
+
To enable the API viewer, use: `allow_api_viewer` in the controller.
|
233
481
|
|
234
482
|
```ruby
|
235
|
-
|
236
|
-
|
483
|
+
class BookController < ActionController::API
|
484
|
+
include MediaTypes::Serialization
|
237
485
|
|
238
|
-
|
486
|
+
allow_api_viewer
|
239
487
|
|
240
|
-
|
241
|
-
|
242
|
-
|
488
|
+
allow_output_serializer(BookSerializer, only: %i[show])
|
489
|
+
allow_input_serializer(BookSerializer, only: %i[create])
|
490
|
+
freeze_io!
|
243
491
|
|
244
|
-
|
492
|
+
def show
|
493
|
+
book = Book.new
|
494
|
+
book.title = 'Everything, abridged'
|
245
495
|
|
246
|
-
|
247
|
-
- `self.wrap(serializer, view: nil)`: to define the wrapper for a specific `view` and/or `serializer`. For example, if
|
248
|
-
you never want to wrap anything, you could define:
|
249
|
-
```ruby
|
250
|
-
def self.wrap(serializer, view: nil)
|
251
|
-
serializer
|
496
|
+
render media: serialize_media(book), content_type: request.format.to_s
|
252
497
|
end
|
253
|
-
```
|
254
498
|
|
255
|
-
|
499
|
+
def create
|
500
|
+
json = deserialize(request, context: self) # does validation for us
|
501
|
+
puts json
|
502
|
+
end
|
503
|
+
end
|
504
|
+
```
|
256
505
|
|
257
|
-
You can
|
506
|
+
You can also output custom HTML:
|
258
507
|
|
259
508
|
```ruby
|
260
|
-
|
261
|
-
|
262
|
-
|
509
|
+
class BookSerializer < MediaTypes::Serialization::Base
|
510
|
+
validator BookValidator
|
511
|
+
|
512
|
+
output versions: [1, 2, 3] do |obj, version, context|
|
513
|
+
attribute :book do
|
514
|
+
link :self, href: context.book_url(obj) if version >= 3
|
515
|
+
|
516
|
+
attribute :title, obj.title
|
517
|
+
attribute :description, obj.description if version >= 2
|
518
|
+
end
|
519
|
+
end
|
520
|
+
|
521
|
+
output_raw view: :html do |obj, context|
|
522
|
+
render_view 'book/show', context: context, assigns: {
|
523
|
+
title: obj.title,
|
524
|
+
description: obj.description
|
525
|
+
}
|
526
|
+
end
|
527
|
+
|
528
|
+
output_alias 'text/html', view: :html
|
263
529
|
end
|
264
530
|
```
|
265
531
|
|
266
|
-
|
267
|
-
`extract_links(view:)`. This will be called by the `to_link_header` function.
|
532
|
+
#### Errors
|
268
533
|
|
269
|
-
|
270
|
-
If you only have `json`/`xml`/structured data responses and you want to use [`media_types-validation`](https://github.com/XPBytes/media_types-validation) in conjunction with this gem, you can create a concern or add the following two functions to your base controller:
|
534
|
+
This library adds support for returning errors to clients using the [`application/problem+json`](https://tools.ietf.org/html/rfc7231) media type. You can catch and transform application errors by adding an `output_error` call before `freeze_io!`:
|
271
535
|
|
272
536
|
```ruby
|
273
|
-
|
274
|
-
|
275
|
-
render media: serializer, content_type: request.format.to_s, **opts
|
276
|
-
validate_media(serializer)
|
277
|
-
end
|
537
|
+
class BookController < ActionController::API
|
538
|
+
include MediaTypes::Serialization
|
278
539
|
|
279
|
-
|
280
|
-
|
281
|
-
|
282
|
-
|
540
|
+
output_error CanCan::AccessDenied do |p, error|
|
541
|
+
p.title 'You do not have enough permissions to perform this action.', lang: 'en'
|
542
|
+
p.title 'Je hebt geen toestemming om deze actie uit te voeren.', lang: 'nl-NL'
|
543
|
+
|
544
|
+
p.status_code :forbidden
|
545
|
+
end
|
546
|
+
|
547
|
+
freeze_io!
|
548
|
+
|
549
|
+
# ...
|
283
550
|
end
|
284
551
|
```
|
285
552
|
|
286
|
-
|
553
|
+
The exception you specified will be rescued by the controller and will be displayed to the user along with a link to the shared wiki page for that error type. Feel free to add instructions there on how clients should solve this problem. You can find more information at: [https://docs.delftsolutions.nl/wiki/Error](https://docs.delftsolutions.nl/wiki/Error)
|
554
|
+
If you want to override this url you can use the `p.url(href)` function.
|
555
|
+
|
556
|
+
By default the `message` property of the error is used to fill the `details` field. You can override this by using the `p.override_details(description, lang:)` function.
|
557
|
+
|
558
|
+
Custom attributes can be added using the `p.attribute(name, value)` function.
|
287
559
|
|
288
560
|
### Related
|
289
561
|
|
290
|
-
- [`MediaTypes`](https://github.com/SleeplessByte/media-types-ruby): :gem: Library to create media type
|
291
|
-
|
292
|
-
|
562
|
+
- [`MediaTypes`](https://github.com/SleeplessByte/media-types-ruby): :gem: Library to create media type validators.
|
563
|
+
|
564
|
+
## API
|
565
|
+
|
566
|
+
### Serializer definition
|
567
|
+
|
568
|
+
These methods become available during class definition if you inherit from `MediaTypes::Serialization::Base`.
|
569
|
+
|
570
|
+
#### `unvalidated( prefix )`
|
571
|
+
|
572
|
+
Disabled validation for this serializer. Prefix is of the form `application/vnd.<organisation>.<name>`.
|
573
|
+
|
574
|
+
Either unvalidated or validator must be used while defining a serializer.
|
575
|
+
|
576
|
+
#### `validator( media_type_validator )`
|
577
|
+
|
578
|
+
Enabled validation for this serializer using a [Media Type Validator](https://github.com/SleeplessByte/media-types-ruby).
|
579
|
+
|
580
|
+
Either validator or unvalidated must be used while defining a serializer.
|
581
|
+
|
582
|
+
#### `output( view:, version:, versions: ) do |obj, version, context|`
|
583
|
+
|
584
|
+
Defines a serialization block. Either version or versions can be set. View should be a symbol or unset.
|
585
|
+
|
586
|
+
Obj is the object to be serialized, version is the negotiated version and context is the context passed in from the serialize function. When using the controller integration, context is the current controller.
|
587
|
+
|
588
|
+
The block should return an object to convert into JSON.
|
589
|
+
|
590
|
+
#### `output_raw( view:, version:, versions: ) do |obj, version, context|`
|
591
|
+
|
592
|
+
This has the same behavior as `output` but should return a string instead of an object. Output is not validated.
|
593
|
+
|
594
|
+
#### `output_alias( media_type_identifier, view:, hide_variant: false )`
|
595
|
+
|
596
|
+
Defines a legacy mapping. This will make the deserializer parse the media type `media_type_identifier` as if it was version `nil` of the specified view. If view is undefined it will use the output serializer without a view defined.
|
597
|
+
|
598
|
+
Response will have a content type equal to `[media_type_identifier]; variant=[mapped_media_type_identifier]`. If `hide_variant:` is true, the content type emitted will only be `[media_type_identifier]`.
|
599
|
+
|
600
|
+
#### `output_alias_optional( media_type_identifier, view:, hide_variant: false )`
|
601
|
+
|
602
|
+
Has the same behavior as `output_alias` but can be used by multiple serializers. The serializer that is loaded last in the controller 'wins' control over this media type identifier. If any of the serializers have an `output_alias` defined with the same media type identifier that one will win instead.
|
603
|
+
|
604
|
+
Response will have a content type equal to `[media_type_identifier]; variant=[mapped_media_type_identifier]`. If `hide_variant:` is true, the content type emitted will only be `[media_type_identifier]`.
|
605
|
+
|
606
|
+
#### `input( view:, version:, versions: ) do |obj, version, context|`
|
607
|
+
|
608
|
+
Defines a deserialization block. Either version or versions can be set. View should be a symbol or unset.
|
609
|
+
|
610
|
+
Obj is the object to be serialized, version is the negotiated version and context is the context passed in from the serialize function. When using the controller integration, context is the current controller.
|
611
|
+
|
612
|
+
The block should return the internal representation of the object. Best practise is to make sure not to change state in this function but to leave that up to the controller.
|
613
|
+
|
614
|
+
#### `input_raw( view:, version:, versions: ) do |bytes, version, context|`
|
615
|
+
|
616
|
+
This has the same behavior as `input` but takes in raw data. Input is not validated.
|
617
|
+
|
618
|
+
#### `input_alias( media_type_identifier, view: )`
|
619
|
+
|
620
|
+
Defines a legacy mapping. This will make the serializer parse the media type `media_type_identifier` as if it was version 1 of the specified view. If view is undefined it will use the input serializer without a view defined.
|
621
|
+
|
622
|
+
#### `input_alias_optional( media_type_identifier, view: )`
|
623
|
+
|
624
|
+
Has the same behavior as `input_alias` but can be used by multiple serializers. The serializer that is loaded last in the controller 'wins' control over this media type identifier. If any of the serializers have an `input_alias` defined with the same media type identifier that one will win instead.
|
625
|
+
|
626
|
+
#### `disable_wildcards`
|
627
|
+
|
628
|
+
Disables registering wildcard media types.
|
629
|
+
|
630
|
+
### Serializer definition
|
631
|
+
|
632
|
+
The following methods are available within an `output ... do` block.
|
633
|
+
|
634
|
+
#### `attribute( key, value = {} ) do`
|
635
|
+
|
636
|
+
Sets a value for the given key. If a block is given, any `attribute`, `link`, `collection` and `index` statements are run in context of `value`.
|
637
|
+
|
638
|
+
Returns the built up context so far.
|
639
|
+
|
640
|
+
#### `link( rel, href:, emit_header: true, **attributes )`
|
641
|
+
|
642
|
+
Adds a `_link` block to the current context. Also adds the specified link to the HTTP Link header. `attributes` allows passing in custom attributes.
|
643
|
+
|
644
|
+
If `emit_header` is `true` the link will also be emitted as a http header.
|
645
|
+
|
646
|
+
Returns the built up context so far.
|
647
|
+
|
648
|
+
#### `index( array, serializer, version:, view: nil )`
|
649
|
+
|
650
|
+
Adds an `_index` block to the current context. Uses the self links of the specified view to construct an index of urls to the child objects.
|
651
|
+
|
652
|
+
Returns the built up context so far.
|
653
|
+
|
654
|
+
#### `collection( array, serializer, version:, view: nil )`
|
655
|
+
|
656
|
+
Adds an `_embedded` block to the current context. Uses the specified serializer to embed the child objects.
|
657
|
+
Optionally a block can be used to modify the output from the child serializer.
|
658
|
+
|
659
|
+
Returns the built up context so far.
|
660
|
+
|
661
|
+
#### `hidden do`
|
662
|
+
|
663
|
+
Sometimes you want to add links without actually modifying the object. Calls to `attribute`, `link`, `index`, `collection` made inside this block won't modify the context. Any calls to link will only set the HTTP Link header.
|
664
|
+
|
665
|
+
Returns the unmodified context.
|
666
|
+
|
667
|
+
#### `emit`
|
668
|
+
|
669
|
+
Can be added to the end of a block to fix up the return value to return the built up context so far.
|
670
|
+
|
671
|
+
Returns the built up context so far.
|
672
|
+
|
673
|
+
#### `object do`
|
674
|
+
|
675
|
+
Runs a block in a new context and returns the result
|
676
|
+
|
677
|
+
#### `render_view( view, context:, **args)`
|
678
|
+
|
679
|
+
Can be used to render a view. You can set local variables in the view by assigning a hash to the `assigns:` parameter.
|
680
|
+
|
681
|
+
### Controller definition
|
682
|
+
|
683
|
+
These functions are available during the controller definition if you add `include MediaTypes::Serialization`.
|
684
|
+
|
685
|
+
#### `allow_output_serializer( serializer, views: nil, **filters )`
|
686
|
+
|
687
|
+
Configure the controller to allow the client to request responses emitted by the specified serializer. Optionally allows you to specify which views to allow by passing an array in the views parameter.
|
688
|
+
|
689
|
+
Accepts the same filters as `before_action`.
|
690
|
+
|
691
|
+
#### `allow_output_html( as: nil, layout: nil, **filters )`
|
692
|
+
|
693
|
+
Allows falling back to the default Rails view rendering when the client asks for the media type in the `as:` parameter or `text/html` if `as:` is unset.
|
694
|
+
|
695
|
+
The `Content-Type` of the response will be `text/html` if the `as:` parameter is unset. If the `as:` parameter is set, it will include it in the variant parameter: `text/html; variant=application/vnd.xpbytes.borderless`.
|
696
|
+
|
697
|
+
Accepts the same filters as `before_action`.
|
698
|
+
|
699
|
+
#### `allow_output_docs( description, **filters )`
|
700
|
+
|
701
|
+
Outputs the specified description as help information.
|
702
|
+
|
703
|
+
Accepts the same filters as `before_action`.
|
704
|
+
|
705
|
+
#### `allow_input_serializer( serializer, views: nil, **filters )`
|
706
|
+
|
707
|
+
Configure the controller to allow the client to send bodies with a `Content-Type` that can be deserialized using the specified serializer. Optionally allows you to specify which views to allow by passing an array in the views parameter.
|
708
|
+
|
709
|
+
Accepts the same filters as `before_action`.
|
710
|
+
|
711
|
+
#### `allow_all_input( **filters )`
|
712
|
+
|
713
|
+
Disables input deserialization. Running `deserialize` while allowing all input will result in an error being thrown.
|
714
|
+
|
715
|
+
#### `not_acceptable_serializer( serializer )`
|
716
|
+
|
717
|
+
Replaces the serializer used to render the error page when no media type could be negotiated using the `Accept` header.
|
718
|
+
|
719
|
+
#### `unsupported_media_type_serializer( serializer )`
|
720
|
+
|
721
|
+
Adds a serializer that can be used to render the error page when the client submits a body with a `Content-Type` that was not added to the whitelist using `allow_input_serialization`.
|
722
|
+
|
723
|
+
#### `clear_unsupported_media_type_serializers!`
|
724
|
+
|
725
|
+
Clears the list of serializers used to render the error when the client supplies non-valid input.
|
726
|
+
|
727
|
+
#### `input_validation_failed_serializer( serializer )`
|
728
|
+
|
729
|
+
Adds a serializer that can be used to render the error page when input validation fails.
|
730
|
+
|
731
|
+
#### `clear_input_validation_failed_serializers!`
|
732
|
+
|
733
|
+
Clears the list of serializers used to render the error when the client supplies non-valid input.
|
734
|
+
|
735
|
+
#### `allow_api_viewer(serializer: MediaTypes::Serialization::Serializers::ApiViewer, **filter_opts)`
|
736
|
+
|
737
|
+
Enables rendering the api viewer when adding the `api_viewer=last` query parameter to the url.
|
738
|
+
|
739
|
+
#### `freeze_io!(**filter_opts)`
|
740
|
+
|
741
|
+
Registers serialization and deserialization in the controller. This function must be called before using the controller.
|
742
|
+
|
743
|
+
### Controller usage
|
744
|
+
|
745
|
+
These functions are available during method execution in the controller.
|
746
|
+
|
747
|
+
#### `render_media( obj, serializers: nil, not_acceptable_serializer: nil, **options ) do`
|
748
|
+
|
749
|
+
Serializes an object and renders it using the appropriate content type. Options are passed through to the controller `render` function. Allows you to specify different objects to different serializers using a block:
|
750
|
+
|
751
|
+
```ruby
|
752
|
+
render_media do
|
753
|
+
serializer BookSerializer, book
|
754
|
+
serializer BooksSerializer do
|
755
|
+
[ book ]
|
756
|
+
end
|
757
|
+
end
|
758
|
+
```
|
759
|
+
|
760
|
+
Warning: this block can be called multiple times when used together with recursive serializers like the API viewer. Try to avoid changing state in this block.
|
761
|
+
|
762
|
+
If you want to render with different serializers than defined in the controller you can pass an array of serializers in the `serializers` property.
|
763
|
+
|
764
|
+
If you want to override the serializer that is used to render the response when no acceptable Content-Type could be negotiated you can pass the desired serializer in the `not_acceptable_serializer` property.
|
765
|
+
|
766
|
+
This method throws a `MediaTypes::Serialization::OutputValidationFailedError` error if the output does not conform to the format defined by the configured validator. Best practise is to return a 500 error to the client.
|
767
|
+
|
768
|
+
If no acceptable Content-Type could be negotiated the response will be rendered using the serialized defined by the class `not_acceptable_serializer` function or by the `not_acceptable_serializer` property.
|
769
|
+
|
770
|
+
Due to the way this gem is implemented it is not possible to use instance variables (`@variable`) in the `render_media` do block.
|
771
|
+
|
772
|
+
#### `deserialize( request )`
|
773
|
+
|
774
|
+
Deserializes the request body using the configured input serializers and returns the deserialized object.
|
775
|
+
|
776
|
+
Returns nil if no input body was given by the client.
|
777
|
+
|
778
|
+
This method throws a `MediaTypes::Serialization::InputValidationFailedError` error if the incoming data does not conform to the specified schema.
|
779
|
+
|
780
|
+
#### `deserialize!( request )`
|
781
|
+
|
782
|
+
Does the same as `deserialize( request )` but gives the client an error page if no input was supplied.
|
783
|
+
|
784
|
+
#### `resolve_serializer(request, identifier = nil, registration = @serialization_output_registration)`
|
785
|
+
|
786
|
+
Returns the serializer class that will handle the given request.
|
787
|
+
|
788
|
+
## Customization
|
789
|
+
|
790
|
+
The easiest way to customize the look and feel of the built in pages is to provide your own logo and background in an initializer:
|
791
|
+
|
792
|
+
```ruby
|
793
|
+
# config/initializers/serialization.rb
|
794
|
+
|
795
|
+
MediaTypes::Serialization::Serializers::CommonCSS.background = 'linear-gradient(245deg, #3a2f28 0%, #201a16 100%)'
|
796
|
+
MediaTypes::Serialization::Serializers::CommonCSS.logo_width = 12
|
797
|
+
MediaTypes::Serialization::Serializers::CommonCSS.logo_data = <<-HERE
|
798
|
+
<svg height="150" width="500">
|
799
|
+
<ellipse cx="240" cy="100" rx="220" ry="30" style="fill:purple" />
|
800
|
+
<ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
|
801
|
+
<ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
|
802
|
+
</svg>
|
803
|
+
HERE
|
804
|
+
```
|
293
805
|
|
294
806
|
## Development
|
295
807
|
|