This repository was archived by the owner on Dec 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_api.rb
More file actions
553 lines (521 loc) · 20.2 KB
/
json_api.rb
File metadata and controls
553 lines (521 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# {http://jsonapi.org/format/ JSON API specification}
# rubocop:disable Style/AsciiComments
# TODO: implement!
# ☐ https://github.com/rails-api/active_model_serializers/issues/1235
# TODO: use uri_template in link generation?
# ☐ https://github.com/rails-api/active_model_serializers/pull/1282#discussion_r42528812
# see gem https://github.com/hannesg/uri_template
# spec http://tools.ietf.org/html/rfc6570
# impl https://developer.github.com/v3/#schema https://api.github.com/
# TODO: validate against a JSON schema document?
# ☐ https://github.com/rails-api/active_model_serializers/issues/1162
# ☑ https://github.com/rails-api/active_model_serializers/pull/1270
# TODO: Routing
# ☐ https://github.com/rails-api/active_model_serializers/pull/1476
# TODO: Query Params
# ☑ `include` https://github.com/rails-api/active_model_serializers/pull/1131
# ☑ `fields` https://github.com/rails-api/active_model_serializers/pull/700
# ☑ `page[number]=3&page[size]=1` https://github.com/rails-api/active_model_serializers/pull/1041
# ☐ `filter`
# ☐ `sort`
module ActiveModelSerializers
module Adapter
class JsonApi < Base
extend ActiveSupport::Autoload
autoload :Jsonapi
autoload :ResourceIdentifier
autoload :Relationship
autoload :Link
autoload :PaginationLinks
autoload :Meta
autoload :Error
autoload :Deserialization
def self.default_key_transform
:dash
end
def self.fragment_cache(cached_hash, non_cached_hash, root = true)
core_cached = cached_hash.first
core_non_cached = non_cached_hash.first
no_root_cache = cached_hash.delete_if { |key, _value| key == core_cached[0] }
no_root_non_cache = non_cached_hash.delete_if { |key, _value| key == core_non_cached[0] }
cached_resource = (core_cached[1]) ? core_cached[1].deep_merge(core_non_cached[1]) : core_non_cached[1]
hash = root ? { root => cached_resource } : cached_resource
hash.deep_merge no_root_non_cache.deep_merge no_root_cache
end
def initialize(serializer, options = {})
super
@include_directive = JSONAPI::IncludeDirective.new(options[:include], allow_wildcard: true)
@fieldset = options[:fieldset] || ActiveModel::Serializer::Fieldset.new(options.delete(:fields))
end
# {http://jsonapi.org/format/#crud Requests are transactional, i.e. success or failure}
# {http://jsonapi.org/format/#document-top-level data and errors MUST NOT coexist in the same document.}
def serializable_hash(*)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:58 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
if serializer.success?
puts "\n\ActiveModelSerializers::Adapter::JsonApi:60 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
document = success_document
puts "\n\ActiveModelSerializers::Adapter::JsonApi:62 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
else
puts "\n\ActiveModelSerializers::Adapter::JsonApi:64 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
document = failure_document
puts "\n\ActiveModelSerializers::Adapter::JsonApi:66 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
end
puts "\n\ActiveModelSerializers::Adapter::JsonApi:68 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
s = self.class.transform_key_casing!(document, instance_options)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:70 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
s
end
def fragment_cache(cached_hash, non_cached_hash)
root = !instance_options.include?(:include)
self.class.fragment_cache(cached_hash, non_cached_hash, root)
end
# {http://jsonapi.org/format/#document-top-level Primary data}
# definition:
# ☐ toplevel_data (required)
# ☐ toplevel_included
# ☑ toplevel_meta
# ☑ toplevel_links
# ☑ toplevel_jsonapi
# structure:
# {
# data: toplevel_data,
# included: toplevel_included,
# meta: toplevel_meta,
# links: toplevel_links,
# jsonapi: toplevel_jsonapi
# }.reject! {|_,v| v.nil? }
# rubocop:disable Metrics/CyclomaticComplexity
def success_document
puts "\n\ActiveModelSerializers::Adapter::JsonApi:95 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
is_collection = serializer.respond_to?(:each)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:97 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
serializers = is_collection ? serializer : [serializer]
puts "\n\ActiveModelSerializers::Adapter::JsonApi:99 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
primary_data, included = resource_objects_for(serializers)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:101 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
hash = {}
# toplevel_data
# definition:
# oneOf
# resource
# array of unique items of type 'resource'
# null
#
# description:
# The document's "primary data" is a representation of the resource or collection of resources
# targeted by a request.
#
# Singular: the resource object.
#
# Collection: one of an array of resource objects, an array of resource identifier objects, or
# an empty array ([]), for requests that target resource collections.
#
# None: null if the request is one that might correspond to a single resource, but doesn't currently.
# structure:
# if serializable_resource.resource?
# resource
# elsif serializable_resource.collection?
# [
# resource,
# resource
# ]
# else
# nil
# end
hash[:data] = is_collection ? primary_data : primary_data[0]
# toplevel_included
# alias included
# definition:
# array of unique items of type 'resource'
#
# description:
# To reduce the number of HTTP requests, servers **MAY** allow
# responses that include related resources along with the requested primary
# resources. Such responses are called "compound documents".
# structure:
# [
# resource,
# resource
# ]
hash[:included] = included if included.any?
puts "\n\ActiveModelSerializers::Adapter::JsonApi:147 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
Jsonapi.add!(hash)
if instance_options[:links]
hash[:links] ||= {}
hash[:links].update(instance_options[:links])
end
puts "\n\ActiveModelSerializers::Adapter::JsonApi:154 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
if is_collection && serializer.paginated?
hash[:links] ||= {}
hash[:links].update(pagination_links_for(serializer))
end
puts "\n\ActiveModelSerializers::Adapter::JsonApi:159 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
hash[:meta] = instance_options[:meta] unless instance_options[:meta].blank?
hash
end
# rubocop:enable Metrics/CyclomaticComplexity
# {http://jsonapi.org/format/#errors JSON API Errors}
# TODO: look into caching
# definition:
# ☑ toplevel_errors array (required)
# ☐ toplevel_meta
# ☐ toplevel_jsonapi
# structure:
# {
# errors: toplevel_errors,
# meta: toplevel_meta,
# jsonapi: toplevel_jsonapi
# }.reject! {|_,v| v.nil? }
# prs:
# https://github.com/rails-api/active_model_serializers/pull/1004
def failure_document
hash = {}
# PR Please :)
# Jsonapi.add!(hash)
# toplevel_errors
# definition:
# array of unique items of type 'error'
# structure:
# [
# error,
# error
# ]
if serializer.respond_to?(:each)
hash[:errors] = serializer.flat_map do |error_serializer|
Error.resource_errors(error_serializer, instance_options)
end
else
hash[:errors] = Error.resource_errors(serializer, instance_options)
end
hash
end
protected
attr_reader :fieldset
private
# {http://jsonapi.org/format/#document-resource-objects Primary data}
# resource
# definition:
# JSON Object
#
# properties:
# type (required) : String
# id (required) : String
# attributes
# relationships
# links
# meta
#
# description:
# "Resource objects" appear in a JSON API document to represent resources
# structure:
# {
# type: 'admin--some-user',
# id: '1336',
# attributes: attributes,
# relationships: relationships,
# links: links,
# meta: meta,
# }.reject! {|_,v| v.nil? }
# prs:
# type
# https://github.com/rails-api/active_model_serializers/pull/1122
# [x] https://github.com/rails-api/active_model_serializers/pull/1213
# https://github.com/rails-api/active_model_serializers/pull/1216
# https://github.com/rails-api/active_model_serializers/pull/1029
# links
# [x] https://github.com/rails-api/active_model_serializers/pull/1246
# [x] url helpers https://github.com/rails-api/active_model_serializers/issues/1269
# meta
# [x] https://github.com/rails-api/active_model_serializers/pull/1340
def resource_objects_for(serializers)
@primary = []
@included = []
@resource_identifiers = Set.new
puts "\n\ActiveModelSerializers::Adapter::JsonApi:248 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
serializers.each do |serializer|
puts "\n\ActiveModelSerializers::Adapter::JsonApi:250 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
process_resource(serializer, true)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:252 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
end
puts "\n\ActiveModelSerializers::Adapter::JsonApi:255 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
serializers.each { |serializer| process_relationships(serializer, @include_directive) }
puts "\n\ActiveModelSerializers::Adapter::JsonApi:257 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
[@primary, @included]
end
def process_resource(serializer, primary)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:258 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
r = ResourceIdentifier.new(serializer, instance_options)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:265 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
resource_identifier = r.as_json
puts "\n\ActiveModelSerializers::Adapter::JsonApi:267 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
return false unless @resource_identifiers.add?(resource_identifier)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:270 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
resource_object = resource_object_for(serializer)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:272 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
# binding.pry
if primary
@primary << resource_object
else
@included << resource_object
end
true
end
def process_relationships(serializer, include_directive)
serializer.associations(include_directive).each do |association|
process_relationship(association.serializer, include_directive[association.key])
end
end
def process_relationship(serializer, include_directive)
if serializer.respond_to?(:each)
serializer.each { |s| process_relationship(s, include_directive) }
return
end
return unless serializer && serializer.object
return unless process_resource(serializer, false)
process_relationships(serializer, include_directive)
end
# {http://jsonapi.org/format/#document-resource-object-attributes Document Resource Object Attributes}
# attributes
# definition:
# JSON Object
#
# patternProperties:
# ^(?!relationships$|links$)\\w[-\\w_]*$
#
# description:
# Members of the attributes object ("attributes") represent information about the resource
# object in which it's defined.
# Attributes may contain any valid JSON value
# structure:
# {
# foo: 'bar'
# }
def attributes_for(serializer, fields)
serializer.attributes(fields).except(:id)
end
# {http://jsonapi.org/format/#document-resource-objects Document Resource Objects}
def resource_object_for(serializer)
resource_object = serializer.fetch(self) do
puts "\n\ActiveModelSerializers::Adapter::JsonApi:323 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
resource_object = ResourceIdentifier.new(serializer, instance_options).as_json
puts "\n\ActiveModelSerializers::Adapter::JsonApi:325 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
requested_fields = fieldset && fieldset.fields_for(resource_object[:type])
puts "\n\ActiveModelSerializers::Adapter::JsonApi:327 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
attributes = attributes_for(serializer, requested_fields)
puts "\n\ActiveModelSerializers::Adapter::JsonApi:329 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
resource_object[:attributes] = attributes if attributes.any?
puts "\n\ActiveModelSerializers::Adapter::JsonApi:331 REQUEST...#{DateTime.now.strftime('%Q')}\n\n"
resource_object
end
requested_associations = fieldset.fields_for(resource_object[:type]) || '*'
relationships = relationships_for(serializer, requested_associations)
resource_object[:relationships] = relationships if relationships.any?
links = links_for(serializer)
# toplevel_links
# definition:
# allOf
# ☐ links
# ☐ pagination
#
# description:
# Link members related to the primary data.
# structure:
# links.merge!(pagination)
# prs:
# https://github.com/rails-api/active_model_serializers/pull/1247
# https://github.com/rails-api/active_model_serializers/pull/1018
resource_object[:links] = links if links.any?
# toplevel_meta
# alias meta
# definition:
# meta
# structure
# {
# :'git-ref' => 'abc123'
# }
meta = meta_for(serializer)
resource_object[:meta] = meta unless meta.blank?
resource_object
end
# {http://jsonapi.org/format/#document-resource-object-relationships Document Resource Object Relationship}
# relationships
# definition:
# JSON Object
#
# patternProperties:
# ^\\w[-\\w_]*$"
#
# properties:
# data : relationshipsData
# links
# meta
#
# description:
#
# Members of the relationships object ("relationships") represent references from the
# resource object in which it's defined to other resource objects."
# structure:
# {
# links: links,
# meta: meta,
# data: relationshipsData
# }.reject! {|_,v| v.nil? }
#
# prs:
# links
# [x] https://github.com/rails-api/active_model_serializers/pull/1454
# meta
# [x] https://github.com/rails-api/active_model_serializers/pull/1454
# polymorphic
# [ ] https://github.com/rails-api/active_model_serializers/pull/1420
#
# relationshipsData
# definition:
# oneOf
# relationshipToOne
# relationshipToMany
#
# description:
# Member, whose value represents "resource linkage"
# structure:
# if has_one?
# relationshipToOne
# else
# relationshipToMany
# end
#
# definition:
# anyOf
# null
# linkage
#
# relationshipToOne
# description:
#
# References to other resource objects in a to-one ("relationship"). Relationships can be
# specified by including a member in a resource's links object.
#
# None: Describes an empty to-one relationship.
# structure:
# if has_related?
# linkage
# else
# nil
# end
#
# relationshipToMany
# definition:
# array of unique items of type 'linkage'
#
# description:
# An array of objects each containing "type" and "id" members for to-many relationships
# structure:
# [
# linkage,
# linkage
# ]
# prs:
# polymorphic
# [ ] https://github.com/rails-api/active_model_serializers/pull/1282
#
# linkage
# definition:
# type (required) : String
# id (required) : String
# meta
#
# description:
# The "type" and "id" to non-empty members.
# structure:
# {
# type: 'required-type',
# id: 'required-id',
# meta: meta
# }.reject! {|_,v| v.nil? }
def relationships_for(serializer, requested_associations)
include_directive = JSONAPI::IncludeDirective.new(
requested_associations,
allow_wildcard: true
)
serializer.associations(include_directive).each_with_object({}) do |association, hash|
hash[association.key] = Relationship.new(
serializer,
association.serializer,
instance_options,
options: association.options,
links: association.links,
meta: association.meta
).as_json
end
end
# {http://jsonapi.org/format/#document-links Document Links}
# links
# definition:
# JSON Object
#
# properties:
# self : URI
# related : link
#
# description:
# A resource object **MAY** contain references to other resource objects ("relationships").
# Relationships may be to-one or to-many. Relationships can be specified by including a member
# in a resource's links object.
#
# A `self` member’s value is a URL for the relationship itself (a "relationship URL"). This
# URL allows the client to directly manipulate the relationship. For example, it would allow
# a client to remove an `author` from an `article` without deleting the people resource
# itself.
# structure:
# {
# self: 'http://example.com/etc',
# related: link
# }.reject! {|_,v| v.nil? }
def links_for(serializer)
serializer._links.each_with_object({}) do |(name, value), hash|
result = Link.new(serializer, value).as_json
hash[name] = result if result
end
end
# {http://jsonapi.org/format/#fetching-pagination Pagination Links}
# pagination
# definition:
# first : pageObject
# last : pageObject
# prev : pageObject
# next : pageObject
# structure:
# {
# first: pageObject,
# last: pageObject,
# prev: pageObject,
# next: pageObject
# }
#
# pageObject
# definition:
# oneOf
# URI
# null
#
# description:
# The <x> page of data
# structure:
# if has_page?
# 'http://example.com/some-page?page[number][x]'
# else
# nil
# end
# prs:
# https://github.com/rails-api/active_model_serializers/pull/1041
def pagination_links_for(serializer)
PaginationLinks.new(serializer.object, instance_options).as_json
end
# {http://jsonapi.org/format/#document-meta Docment Meta}
def meta_for(serializer)
Meta.new(serializer).as_json
end
end
end
end
# rubocop:enable Style/AsciiComments