json_api_server 0.0.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.dockerignore +7 -0
- data/.gitignore +14 -0
- data/.rspec +2 -0
- data/.rubocop.yml +35 -0
- data/.travis.yml +5 -0
- data/CODE_OF_CONDUCT.md +74 -0
- data/Dockerfile +9 -0
- data/Gemfile +10 -0
- data/LICENSE.txt +21 -0
- data/README.md +432 -0
- data/Rakefile +6 -0
- data/bin/console +14 -0
- data/bin/setup +8 -0
- data/config/locales/en.yml +32 -0
- data/docker-compose.yml +10 -0
- data/json_api_server.gemspec +50 -0
- data/lib/json_api_server.rb +76 -0
- data/lib/json_api_server/api_version.rb +8 -0
- data/lib/json_api_server/attributes_builder.rb +135 -0
- data/lib/json_api_server/base_serializer.rb +169 -0
- data/lib/json_api_server/builder.rb +201 -0
- data/lib/json_api_server/cast.rb +89 -0
- data/lib/json_api_server/configuration.rb +99 -0
- data/lib/json_api_server/controller/error_handling.rb +164 -0
- data/lib/json_api_server/engine.rb +5 -0
- data/lib/json_api_server/error.rb +64 -0
- data/lib/json_api_server/errors.rb +50 -0
- data/lib/json_api_server/exceptions.rb +6 -0
- data/lib/json_api_server/fields.rb +76 -0
- data/lib/json_api_server/filter.rb +255 -0
- data/lib/json_api_server/filter_builders.rb +135 -0
- data/lib/json_api_server/filter_config.rb +71 -0
- data/lib/json_api_server/filter_parser.rb +88 -0
- data/lib/json_api_server/include.rb +158 -0
- data/lib/json_api_server/meta_builder.rb +39 -0
- data/lib/json_api_server/mime_types.rb +21 -0
- data/lib/json_api_server/pagination.rb +189 -0
- data/lib/json_api_server/paginator.rb +134 -0
- data/lib/json_api_server/relationships_builder.rb +215 -0
- data/lib/json_api_server/resource_serializer.rb +245 -0
- data/lib/json_api_server/resources_serializer.rb +131 -0
- data/lib/json_api_server/serializer.rb +34 -0
- data/lib/json_api_server/sort.rb +156 -0
- data/lib/json_api_server/sort_configs.rb +63 -0
- data/lib/json_api_server/validation_errors.rb +51 -0
- data/lib/json_api_server/version.rb +3 -0
- metadata +259 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA1:
|
3
|
+
metadata.gz: 0c194229175b097b7ccda00f8ee5ca3eae2112d0
|
4
|
+
data.tar.gz: 40915f4a3054c9b734b8b6b85557c7fbcca27943
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 8f7719d5a686ba555f117b55d884d03738940efbfd3c6aa5938f9cc1bee2731a9289acb49656629a2ed18fc5f9c74946d1530d9da057c6feed3180c0481e37b8
|
7
|
+
data.tar.gz: eee640d529fa50d6cbff7947d7f43bac2cbb9167a2e1d5ea9f2ac7b7c9eb1af524356fac79d82104deb8395c8a17bbf4b3041a6aac22f7944ede4566b6a0ad72
|
data/.dockerignore
ADDED
data/.gitignore
ADDED
data/.rspec
ADDED
data/.rubocop.yml
ADDED
@@ -0,0 +1,35 @@
|
|
1
|
+
# inherit_from: .rubocop_todo.yml
|
2
|
+
AllCops:
|
3
|
+
Exclude:
|
4
|
+
- 'spec/test_app/*'
|
5
|
+
Metrics/LineLength:
|
6
|
+
Max: 150
|
7
|
+
Exclude:
|
8
|
+
- 'spec/**/*'
|
9
|
+
Lint/DuplicatedKey:
|
10
|
+
Exclude:
|
11
|
+
- 'spec/controller/filter_spec.rb'
|
12
|
+
Metrics/BlockLength:
|
13
|
+
CountComments: false
|
14
|
+
Exclude:
|
15
|
+
- 'json_api_server.gemspec'
|
16
|
+
- 'spec/**/*'
|
17
|
+
Lint/UselessComparison:
|
18
|
+
Exclude:
|
19
|
+
- 'spec/json_api_server/attributes_builder_spec.rb'
|
20
|
+
- 'spec/json_api_server/relationships_builder_spec.rb'
|
21
|
+
Style/Documentation:
|
22
|
+
Exclude:
|
23
|
+
- 'spec/**/*'
|
24
|
+
Metrics/CyclomaticComplexity:
|
25
|
+
Max: 9
|
26
|
+
Metrics/AbcSize:
|
27
|
+
Max: 25
|
28
|
+
Style/GuardClause:
|
29
|
+
Exclude:
|
30
|
+
- 'lib/json_api_server/filter_builders.rb'
|
31
|
+
- 'lib/json_api_server/pagination.rb'
|
32
|
+
- 'lib/json_api_server/relationships_builder.rb'
|
33
|
+
- 'lib/json_api_server/validation_errors.rb'
|
34
|
+
Metrics/MethodLength:
|
35
|
+
Max: 20
|
data/.travis.yml
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,74 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
In the interest of fostering an open and welcoming environment, we as
|
6
|
+
contributors and maintainers pledge to making participation in our project and
|
7
|
+
our community a harassment-free experience for everyone, regardless of age, body
|
8
|
+
size, disability, ethnicity, gender identity and expression, level of experience,
|
9
|
+
nationality, personal appearance, race, religion, or sexual identity and
|
10
|
+
orientation.
|
11
|
+
|
12
|
+
## Our Standards
|
13
|
+
|
14
|
+
Examples of behavior that contributes to creating a positive environment
|
15
|
+
include:
|
16
|
+
|
17
|
+
* Using welcoming and inclusive language
|
18
|
+
* Being respectful of differing viewpoints and experiences
|
19
|
+
* Gracefully accepting constructive criticism
|
20
|
+
* Focusing on what is best for the community
|
21
|
+
* Showing empathy towards other community members
|
22
|
+
|
23
|
+
Examples of unacceptable behavior by participants include:
|
24
|
+
|
25
|
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
26
|
+
advances
|
27
|
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
28
|
+
* Public or private harassment
|
29
|
+
* Publishing others' private information, such as a physical or electronic
|
30
|
+
address, without explicit permission
|
31
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
32
|
+
professional setting
|
33
|
+
|
34
|
+
## Our Responsibilities
|
35
|
+
|
36
|
+
Project maintainers are responsible for clarifying the standards of acceptable
|
37
|
+
behavior and are expected to take appropriate and fair corrective action in
|
38
|
+
response to any instances of unacceptable behavior.
|
39
|
+
|
40
|
+
Project maintainers have the right and responsibility to remove, edit, or
|
41
|
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
42
|
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
43
|
+
permanently any contributor for other behaviors that they deem inappropriate,
|
44
|
+
threatening, offensive, or harmful.
|
45
|
+
|
46
|
+
## Scope
|
47
|
+
|
48
|
+
This Code of Conduct applies both within project spaces and in public spaces
|
49
|
+
when an individual is representing the project or its community. Examples of
|
50
|
+
representing a project or community include using an official project e-mail
|
51
|
+
address, posting via an official social media account, or acting as an appointed
|
52
|
+
representative at an online or offline event. Representation of a project may be
|
53
|
+
further defined and clarified by project maintainers.
|
54
|
+
|
55
|
+
## Enforcement
|
56
|
+
|
57
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
58
|
+
reported by contacting the project team. All
|
59
|
+
complaints will be reviewed and investigated and will result in a response that
|
60
|
+
is deemed necessary and appropriate to the circumstances. The project team is
|
61
|
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
62
|
+
Further details of specific enforcement policies may be posted separately.
|
63
|
+
|
64
|
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
65
|
+
faith may face temporary or permanent repercussions as determined by other
|
66
|
+
members of the project's leadership.
|
67
|
+
|
68
|
+
## Attribution
|
69
|
+
|
70
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
71
|
+
available at [http://contributor-covenant.org/version/1/4][version]
|
72
|
+
|
73
|
+
[homepage]: http://contributor-covenant.org
|
74
|
+
[version]: http://contributor-covenant.org/version/1/4/
|
data/Dockerfile
ADDED
@@ -0,0 +1,9 @@
|
|
1
|
+
FROM ruby:2.3.3
|
2
|
+
|
3
|
+
ENV GEM_HOME /home/gems/mygem
|
4
|
+
RUN mkdir -p $GEM_HOME
|
5
|
+
# https://docs.docker.com/engine/reference/builder/#workdir
|
6
|
+
WORKDIR $GEM_HOME
|
7
|
+
COPY . $GEM_HOME
|
8
|
+
RUN bundle install
|
9
|
+
# RUN cd spec/test_app &&r rake db:migrate && rake db:migrate RAILS_ENV=test
|
data/Gemfile
ADDED
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2017 ed.mare
|
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
|
13
|
+
all 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
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,432 @@
|
|
1
|
+
# JsonApiServer
|
2
|
+
|
3
|
+
This gem provides tools for building JSON APIs per http://jsonapi.org spec (1.0).
|
4
|
+
It supports sparse fieldsets, sorting, filtering, pagination, and inclusion of
|
5
|
+
related resources. Sorting, filtering, and inclusions are whitelisted
|
6
|
+
so depth/complexity can be controlled.
|
7
|
+
|
8
|
+
This library: (1) generates data for sorting, filtering,
|
9
|
+
inclusions, and pagination, (2) provides serializers and helper classes for
|
10
|
+
building the response with this data, and (3) handles/renders errors in JSON API format.
|
11
|
+
Otherwise, you build your API as you normally do (i.e, routes, authorization,
|
12
|
+
caching, etc.).
|
13
|
+
|
14
|
+
Use at your own risk. This gem is under development and has not been used
|
15
|
+
in production yet. Known to work with Ruby 2.3.x and Rails 5.x.
|
16
|
+
Supports only ActiveRecord at this time.
|
17
|
+
|
18
|
+
- **Example app** -> https://github.com/ed-mare/jsonapiserver-example
|
19
|
+
- **Documentation** -> Install gem rdoc for more documentation.
|
20
|
+
|
21
|
+
## Installation
|
22
|
+
|
23
|
+
Add this line to your application's Gemfile:
|
24
|
+
|
25
|
+
```ruby
|
26
|
+
gem 'json_api_server'
|
27
|
+
```
|
28
|
+
|
29
|
+
And then execute:
|
30
|
+
|
31
|
+
$ bundle
|
32
|
+
|
33
|
+
Or install it yourself as:
|
34
|
+
|
35
|
+
$ gem install json_api_server
|
36
|
+
|
37
|
+
## Usage
|
38
|
+
|
39
|
+
Install gem rdoc for more documentation.
|
40
|
+
|
41
|
+
##### 1) Include JsonApiServer::Controller::ErrorHandling in your base API controller.
|
42
|
+
|
43
|
+
```ruby
|
44
|
+
# i.e.,
|
45
|
+
class BaseApiController < ApplicationController
|
46
|
+
include JsonApiServer::Controller::ErrorHandling
|
47
|
+
end
|
48
|
+
```
|
49
|
+
|
50
|
+
It provides methods which render errors per http://jsonapi.org/format/#errors:
|
51
|
+
|
52
|
+
- `render_400`, `render_401`, `render_404`, `render_409`, `render_422`, `render_500`,
|
53
|
+
`render_unknown_format`, `render_503`.
|
54
|
+
|
55
|
+
It rescues from and renders JSON API errors for:
|
56
|
+
|
57
|
+
- StandardError (render_500)
|
58
|
+
- JsonApiServer::BadRequest (render_400)
|
59
|
+
- ActionController::BadRequest (render_400)
|
60
|
+
- ActiveRecord::RecordNotFound, ActionController::RoutingError (render_404)
|
61
|
+
- ActiveRecord::RecordNotUnique (render_409)
|
62
|
+
- ActionController::RoutingError (render_404)
|
63
|
+
- ActionController::UrlGenerationError (render_404)
|
64
|
+
- ActionController::UnknownController (render_404)
|
65
|
+
- ActionController::UnknownFormat (render_unknown_format 406)
|
66
|
+
|
67
|
+
Additionally:
|
68
|
+
|
69
|
+
- Use `render_422(object)` in controllers to render validation errors.
|
70
|
+
|
71
|
+
Error messages are defined in 'config/locales/en.yml' and can be customized
|
72
|
+
or redefined.
|
73
|
+
|
74
|
+
i.e.,
|
75
|
+
|
76
|
+
```ruby
|
77
|
+
# Given a sandwiches controller...
|
78
|
+
class Api::V1::SandwichesController < Api::BaseController
|
79
|
+
...
|
80
|
+
end
|
81
|
+
|
82
|
+
# config/locales/en.yml
|
83
|
+
en:
|
84
|
+
json_api_server:
|
85
|
+
controller:
|
86
|
+
sandwiches:
|
87
|
+
name: 'sandwich'
|
88
|
+
|
89
|
+
# messages now become:
|
90
|
+
# 404 => "This sandwich does not exist."
|
91
|
+
# 409 => "This sandwich already exists."
|
92
|
+
```
|
93
|
+
|
94
|
+
##### 2) Include JsonApiServer::MimeTypes in initializers
|
95
|
+
|
96
|
+
Spec: "JSON API requires use of the JSON API media type
|
97
|
+
(application/vnd.api+json) for exchanging data."
|
98
|
+
|
99
|
+
To support this mime type:
|
100
|
+
|
101
|
+
```ruby
|
102
|
+
# config/initializers/mime_types.rb
|
103
|
+
include JsonApiServer::MimeTypes
|
104
|
+
```
|
105
|
+
##### 3) Configure the gem
|
106
|
+
|
107
|
+
Configure the logger, base URL, serialization options and filter builders.
|
108
|
+
|
109
|
+
```ruby
|
110
|
+
# config/initializers/json_api_server.rb
|
111
|
+
JsonApiServer.configure do |c|
|
112
|
+
c.base_url = 'https://www.something.com'
|
113
|
+
c.logger = Rails.logger
|
114
|
+
c.serializer_options = {
|
115
|
+
escape_mode: :json,
|
116
|
+
time: :xmlschema,
|
117
|
+
mode: :compat
|
118
|
+
}
|
119
|
+
end
|
120
|
+
```
|
121
|
+
|
122
|
+
Optionally, set this Rails config so '`&`' is not escaped in pagination URLs:
|
123
|
+
|
124
|
+
```ruby
|
125
|
+
# application.rb
|
126
|
+
config.active_support.escape_html_entities_in_json = false
|
127
|
+
```
|
128
|
+
|
129
|
+
##### 4) Use JsonApiServer::Builder to collect data in the controller.
|
130
|
+
|
131
|
+
This class handles pagination, sorting, filters, inclusion of
|
132
|
+
related resources, and sparse fieldsets. It collects the necessary data for the
|
133
|
+
serializers.
|
134
|
+
|
135
|
+
This class uses the following classes. See each class's rdoc for configuration options.
|
136
|
+
|
137
|
+
- JsonApiServer::Pagination
|
138
|
+
- JsonApiServer::Sort
|
139
|
+
- JsonApiServer::Filter
|
140
|
+
- JsonApiServer::Include
|
141
|
+
- JsonApiServer::Fields
|
142
|
+
|
143
|
+
A variety of search capabilities can be configured for model attributes with
|
144
|
+
`JsonApiServer::Filter` - LIKE queries, ILIKE queries (Postgres), IN queries,
|
145
|
+
comparison queries, range queries, and queries against Postgres jsonb arrays
|
146
|
+
(case sensitive/insensitive). Plus, custom queries and custom filters can be easily
|
147
|
+
added.
|
148
|
+
|
149
|
+
**Example**:
|
150
|
+
|
151
|
+
```ruby
|
152
|
+
class TopicsController < BaseApiController
|
153
|
+
attr_accessor :pagination_options, :sort_options, :filter_options, :include_options
|
154
|
+
|
155
|
+
before_action do |c|
|
156
|
+
# Set a limit on the maximum number of records a user can request per page.
|
157
|
+
# Set the default number of records per page.
|
158
|
+
c.pagination_options = { default_per_page: 10, max_per_page: 60 }
|
159
|
+
|
160
|
+
# Whitelist sortable attributes and set default sort.
|
161
|
+
c.sort_options = {
|
162
|
+
permitted: [:character, :location, :published],
|
163
|
+
default: { id: :desc }
|
164
|
+
}
|
165
|
+
|
166
|
+
# Whitelist filters and configure how to perform the query. There are built-in
|
167
|
+
# query builder classes and custom classes can be plugged in.
|
168
|
+
c.filter_options = [
|
169
|
+
{ id: { type: 'Integer' } },
|
170
|
+
{ published: { type: 'Date' } },
|
171
|
+
:location,
|
172
|
+
{ book: { wildcard: :both } }
|
173
|
+
]
|
174
|
+
|
175
|
+
# Whitelist inclusions and optionally configure eagerloading.
|
176
|
+
c.include_options = [
|
177
|
+
{'publisher': -> { includes(:publisher) }},
|
178
|
+
{'comments': -> { includes(:comments) }},
|
179
|
+
'comment.author'
|
180
|
+
]
|
181
|
+
end
|
182
|
+
|
183
|
+
def index
|
184
|
+
# collect the data
|
185
|
+
builder = JsonApiServer::Builder.new(request, Topic.current)
|
186
|
+
.add_pagination(pagination_options)
|
187
|
+
.add_filter(filter_options)
|
188
|
+
.add_include(include_options)
|
189
|
+
.add_sort(sort_options)
|
190
|
+
.add_fields
|
191
|
+
|
192
|
+
# pass the data to the serializer
|
193
|
+
serializer = TopicsSerializer.from_builder(builder)
|
194
|
+
render json: serializer.to_json, status: :ok
|
195
|
+
end
|
196
|
+
|
197
|
+
def show
|
198
|
+
builder = JsonApiServer::Builder.new(request, Topic.find(params[:id]))
|
199
|
+
.add_include(['publisher', 'comments', 'comments.includes'])
|
200
|
+
.add_fields
|
201
|
+
|
202
|
+
serializer = TopicSerializer.from_builder(builder)
|
203
|
+
render json: serializer.to_json, status: :ok
|
204
|
+
end
|
205
|
+
|
206
|
+
def create
|
207
|
+
topic = Topic.new(topic_params)
|
208
|
+
|
209
|
+
if topic.save
|
210
|
+
serializer = TopicSerializer.new(topic)
|
211
|
+
render json: serializer.to_json, status: :created
|
212
|
+
else
|
213
|
+
render_422(topic) # return validation errors in JSON API format.
|
214
|
+
end
|
215
|
+
end
|
216
|
+
|
217
|
+
protected
|
218
|
+
|
219
|
+
def topic_params
|
220
|
+
params.require(:data)
|
221
|
+
.require(:attributes)
|
222
|
+
.permit(:character, :book, :quote, :location, :published,
|
223
|
+
:author, :publisher_id)
|
224
|
+
end
|
225
|
+
|
226
|
+
end
|
227
|
+
```
|
228
|
+
|
229
|
+
##### 5) Create Serializers
|
230
|
+
|
231
|
+
JsonApiServer serializers use the oj gem (https://github.com/ohler55/oj), a fast JSON parser
|
232
|
+
and Object marshaller. Helper classes
|
233
|
+
JsonApiServer::AttributesBuilder (sparse fieldsets), JsonApiServer::RelationshipsBuilder
|
234
|
+
(relationships/included), JsonApiServer::Paginator (pagination), and JsonApiServer::MetaBuilder (meta)
|
235
|
+
assist with populating serializers.
|
236
|
+
|
237
|
+
Caching is not built into the serializers
|
238
|
+
given the variability of JSON API documents. Low level caching is recommended.
|
239
|
+
|
240
|
+
---
|
241
|
+
|
242
|
+
All serializers inherit from JsonApiServer::BaseSerializer. It creates this structure:
|
243
|
+
|
244
|
+
```ruby
|
245
|
+
{
|
246
|
+
":jsonapi": {
|
247
|
+
":version": "1.0"
|
248
|
+
},
|
249
|
+
":links": null,
|
250
|
+
":data": null,
|
251
|
+
":included": null,
|
252
|
+
":meta": null
|
253
|
+
}
|
254
|
+
```
|
255
|
+
|
256
|
+
Sometimes only part of document is needed, i.e., when embedding one serializer in another.
|
257
|
+
`as_json` takes an optional hash argument which determines which parts of the document to return.
|
258
|
+
These options can also be set in JsonApiServer::BaseSerializer#as_json_options.
|
259
|
+
|
260
|
+
```ruby
|
261
|
+
serializer.as_json(include: [:data]) # => { data: {...} }
|
262
|
+
serializer.as_json(include: [:links]) # => { links: {...} }
|
263
|
+
serializer.as_json(include: [:links, :data]) # =>
|
264
|
+
# {
|
265
|
+
# links: {...},
|
266
|
+
# data: {...}
|
267
|
+
# }
|
268
|
+
```
|
269
|
+
|
270
|
+
---
|
271
|
+
|
272
|
+
JsonApiServer::ResourceSerializer inherits from JsonApiServer::BaseSerializer.
|
273
|
+
It is intended for a single resource (i.e, comment, author). Instantiate with a
|
274
|
+
JsonApiServer::Builder instance:
|
275
|
+
|
276
|
+
**Example**:
|
277
|
+
|
278
|
+
```ruby
|
279
|
+
class TopicSerializer < JsonApiServer::ResourceSerializer
|
280
|
+
resource_type 'topics'
|
281
|
+
|
282
|
+
def links
|
283
|
+
{ self: File.join(base_url, "/topics/#{@object.id}") }
|
284
|
+
end
|
285
|
+
|
286
|
+
def data
|
287
|
+
{
|
288
|
+
type: self.class.type,
|
289
|
+
id: @object.id,
|
290
|
+
attributes: attributes,
|
291
|
+
relationships: inclusions.relationships
|
292
|
+
}
|
293
|
+
end
|
294
|
+
|
295
|
+
def included
|
296
|
+
inclusions.included
|
297
|
+
end
|
298
|
+
|
299
|
+
protected
|
300
|
+
|
301
|
+
def attributes
|
302
|
+
attributes_builder
|
303
|
+
.add_multi(@object, 'book', 'author', 'quote', 'character')
|
304
|
+
.add('location', @object.location)
|
305
|
+
.add('published', @object.published)
|
306
|
+
.add('created_at', @object.created_at.try(:iso8601, 9))
|
307
|
+
.add('updated_at', @object.updated_at.try(:iso8601, 9))
|
308
|
+
.attributes
|
309
|
+
end
|
310
|
+
|
311
|
+
# Example: provide different ways of accessing the same relationship data:
|
312
|
+
#
|
313
|
+
# 1) 'comments' puts all data in the relationship (easier to walk the tree).
|
314
|
+
# 2) 'comments.includes' puts data in the included section and relationship
|
315
|
+
# links to it.
|
316
|
+
def inclusions
|
317
|
+
@inclusions ||= begin
|
318
|
+
if relationship?('publisher')
|
319
|
+
relationships_builder.relate('publisher', publisher_serializer(@object.publisher))
|
320
|
+
end
|
321
|
+
if relationship?('comments')
|
322
|
+
relationships_builder.relate_each('comments', @object.comments) { |c| comment_serializer(c) }
|
323
|
+
elsif relationship?('comments.includes')
|
324
|
+
relationships_builder.include_each('comments.includes', @object.comments, type: 'comments',
|
325
|
+
relate: {include: [:relationship_data]}) { |c| comment_serializer(c) }
|
326
|
+
end
|
327
|
+
|
328
|
+
relationships_builder
|
329
|
+
end
|
330
|
+
end
|
331
|
+
|
332
|
+
# Pass includes and fields to child serializers.
|
333
|
+
def publisher_serializer(publisher, as_json_options=nil)
|
334
|
+
PublisherSerializer.new(publisher, includes: includes, fields: fields,
|
335
|
+
as_json_options: as_json_options || {include: [:data]})
|
336
|
+
end
|
337
|
+
|
338
|
+
# Pass includes and fields to child serializers.
|
339
|
+
def comment_serializer(comment, as_json_options=nil)
|
340
|
+
CommentSerializer.new(comment, includes: includes, fields: fields,
|
341
|
+
as_json_options: as_json_options || {include: [:data]})
|
342
|
+
end
|
343
|
+
end
|
344
|
+
|
345
|
+
# instantiate in controller...
|
346
|
+
builder = JsonApiServer::Builder.new(request, Topic.find(params[:id]))
|
347
|
+
.add_include(['publisher', 'comments', 'comments.includes'])
|
348
|
+
.add_fields
|
349
|
+
serializer = TopicSerializer.from_builder(builder)
|
350
|
+
```
|
351
|
+
|
352
|
+
Helper methods:
|
353
|
+
|
354
|
+
- JsonApiServer::ResourceSerializer#attributes_builder -- returns an instance of
|
355
|
+
JsonApiServer::AttributesBuilder for the 'type' specified in `resource_type`.
|
356
|
+
- JsonApiServer::ResourceSerializer#meta_builder -- returns an instance of
|
357
|
+
JsonApiServer::MetaBuilder for building the meta section.
|
358
|
+
- JsonApiServer::ResourceSerializer#relationships_builder -- returns an instance of
|
359
|
+
JsonApiServer::RelationshipsBuilder with whitelisted includes.
|
360
|
+
- JsonApiServer::ResourceSerializer#relationship? -- returns true if relationship is
|
361
|
+
requested.
|
362
|
+
- JsonApiServer::ResourceSerializer#inclusions? -- returns true if inclusions are
|
363
|
+
requested.
|
364
|
+
---
|
365
|
+
|
366
|
+
JsonApiServer::ResourcesSerializer inherits from JsonApiServer::ResourceSerializer.
|
367
|
+
It serializes a collection of objects with a specified serializer and merges them.
|
368
|
+
It populates the links section with pagination URLs if JsonApiServer::Builder#add_pagination
|
369
|
+
is called.
|
370
|
+
|
371
|
+
**Example**:
|
372
|
+
|
373
|
+
```ruby
|
374
|
+
class TopicSerializer < JsonApiServer::ResourceSerializer
|
375
|
+
...
|
376
|
+
end
|
377
|
+
|
378
|
+
class TopicsSerializer < JsonApiServer::ResourcesSerializer
|
379
|
+
serializer TopicSerializer # serializer for objects
|
380
|
+
end
|
381
|
+
|
382
|
+
builder = JsonApiServer::Builder.new(request, Topic.current)
|
383
|
+
.add_pagination(pagination_options)
|
384
|
+
.add_filter(filter_options)
|
385
|
+
.add_include(include_options)
|
386
|
+
.add_sort(sort_options)
|
387
|
+
.add_fields
|
388
|
+
|
389
|
+
serializer = TopicsSerializer.from_builder(builder)
|
390
|
+
```
|
391
|
+
|
392
|
+
## Development
|
393
|
+
|
394
|
+
1. Build the docker image:
|
395
|
+
|
396
|
+
```shell
|
397
|
+
docker-compose build
|
398
|
+
```
|
399
|
+
|
400
|
+
2. Start docker image with an interactive bash shell:
|
401
|
+
|
402
|
+
```shell
|
403
|
+
docker-compose run --rm gem
|
404
|
+
```
|
405
|
+
|
406
|
+
3. Once in bash session, code, run tests, start console, etc.
|
407
|
+
|
408
|
+
```shell
|
409
|
+
# run console with gem loaded
|
410
|
+
bundle console
|
411
|
+
|
412
|
+
# run tests - to be run from root of gem
|
413
|
+
bundle exec rspec
|
414
|
+
|
415
|
+
# generate rdoc
|
416
|
+
rdoc --main 'README.md' --exclude 'spec' --exclude 'bin' --exclude 'Gemfile' --exclude 'Dockerfile' --exclude 'Rakefile'
|
417
|
+
```
|
418
|
+
|
419
|
+
## Todo
|
420
|
+
|
421
|
+
- Test against multiple rubies/rails.
|
422
|
+
- Clean up tests, esp. as_json which are brittle.
|
423
|
+
- Test against Postgres.
|
424
|
+
- Support Mongoid.
|
425
|
+
|
426
|
+
## Contributing
|
427
|
+
|
428
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/ed-mare/json_api_server. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
|
429
|
+
|
430
|
+
## License
|
431
|
+
|
432
|
+
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
|