@@ -84,19 +84,46 @@ def parse!(document, options = {})
84
84
def parse ( document , options = { } )
85
85
# TODO: change to jsonapi-ralis to have default conversion to flat hashes
86
86
result = JSONAPI ::Rails ::DeserializableResource . new ( document , options : options ) . to_hash
87
- result = transform_keys ( result ) if options [ :key_transform ]
87
+ result = apply_options ( result , options )
88
88
result
89
89
rescue JSONAPI ::Parser ::InvalidDocument => e
90
90
return { } unless block_given?
91
91
yield e
92
92
end
93
93
94
+ def apply_options ( hash , options )
95
+ hash = transform_keys ( hash , options ) if options [ :key_transform ]
96
+ hash = hash . deep_symbolize_keys
97
+ hash = filter_fields ( hash , options )
98
+ hash = rename_fields ( hash , options )
99
+ hash
100
+ end
101
+
94
102
# TODO: transform the keys after parsing
95
103
# @api private
96
104
def transform_keys ( hash , options )
97
105
transform = options [ :key_transform ] || :underscore
98
106
CaseTransform . send ( transform , hash )
99
107
end
108
+
109
+ # executes only
110
+ # then except
111
+ def filter_fields ( hash , options )
112
+ hash = hash . select { |k , v | options [ :only ] . include? ( k ) } if options [ :only ]
113
+ hash = hash . select { |k , v | !options [ :except ] . include? ( k ) } if options [ :except ]
114
+ hash
115
+ end
116
+
117
+ def rename_fields ( hash , options )
118
+ return hash unless options [ :keys ]
119
+
120
+ keys = options [ :keys ]
121
+ hash . each_with_object ( { } ) do |( k , v ) , h |
122
+ k = keys . fetch ( k , k )
123
+ h [ k ] = v
124
+ h
125
+ end
126
+ end
100
127
end
101
128
end
102
129
end
0 commit comments