-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathdeserialization.rb
More file actions
87 lines (77 loc) · 2.71 KB
/
deserialization.rb
File metadata and controls
87 lines (77 loc) · 2.71 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
begin
require 'active_support/inflector'
rescue LoadError
warn(
'Trying to load `dry-inflector` as an ' \
'alternative to `active_support/inflector`...'
)
require 'dry/inflector'
end
module JSONAPI
# Helpers to transform a JSON API document, containing a single data object,
# into a hash that can be used to create an [ActiveRecord::Base] instance.
#
# Initial version from the `active_model_serializers` support for JSONAPI.
module Deserialization
private
# Helper method to pick an available inflector implementation
#
# @return [Object]
def jsonapi_inflector
ActiveSupport::Inflector
rescue
Dry::Inflector.new
end
# Returns a transformed dictionary following [ActiveRecord::Base] specs
#
# @param [Hash|ActionController::Parameters] document
# @param [Hash] options
# only: Array of symbols of whitelisted fields.
# except: Array of symbols of blacklisted fields.
# polymorphic: Array of symbols of polymorphic fields.
# @return [Hash]
def jsonapi_deserialize(document, options = {})
if document.respond_to?(:permit!)
# Handle Rails params...
primary_data = document.dup.require(:data).permit!.as_json
elsif document.is_a?(Hash)
primary_data = (document.as_json['data'] || {}).deep_dup
else
return {}
end
# Transform keys and any option values.
options = options.as_json
['only', 'except', 'polymorphic', 'symbolize_keys'].each do |opt_name|
opt_value = options[opt_name]
options[opt_name] = Array(opt_value).map(&:to_s) if opt_value
end
relationships = primary_data['relationships'] || {}
parsed = primary_data['attributes'] || {}
parsed['id'] = primary_data['id'] if primary_data['id']
# Remove unwanted items from a dictionary.
if options['only']
[parsed, relationships].map { |hsh| hsh.slice!(*options['only']) }
elsif options['except']
[parsed, relationships].map { |hsh| hsh.except!(*options['except']) }
end
relationships.map do |assoc_name, assoc_data|
assoc_data = (assoc_data || {})['data'] || {}
rel_name = jsonapi_inflector.singularize(assoc_name)
if assoc_data.is_a?(Array)
parsed["#{rel_name}_ids"] = assoc_data.map { |ri| ri['id'] }.compact
next
end
parsed["#{rel_name}_id"] = assoc_data['id']
if (options['polymorphic'] || []).include?(assoc_name)
rel_type = jsonapi_inflector.classify(assoc_data['type'].to_s)
parsed["#{rel_name}_type"] = rel_type
end
end
if options['symbolize_keys']
parsed.symbolize_keys
else
parsed
end
end
end
end