json_api_deserializer 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5ea4c75b7feec885eccd2c1da4e893343432652c118dd9e0a54aa17661fe91a0
4
+ data.tar.gz: 5e7b2fb6b6ad99e3fa4743fd8a37a0b42f3356d40e0de95558a12dfdec44d896
5
+ SHA512:
6
+ metadata.gz: 3e13c55af8ea36b8920e03d45a39181a8cc632ca6bfdb8be93f887240e1c0fdecc6624ab9db08d157845cf4220afa836dd0b9d53095fae46133861d61b78faee
7
+ data.tar.gz: ce696c38d23044bbb687456e2bea57dabda40971ed41fbb7666d6b395cddcada0b4ad30088c3ab6a4e68d2f691de57d5ff5837f0de000166e09fe025ee7477b8
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.2
7
+ before_install: gem install bundler -v 2.0.1
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in json_api_deserializer.gemspec
4
+
5
+ group :development do
6
+ gem 'pry'
7
+ gem 'rubocop'
8
+ end
9
+
10
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,71 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ json_api_deserializer (0.1.0)
5
+ activesupport
6
+ case_transform
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ activesupport (5.2.3)
12
+ concurrent-ruby (~> 1.0, >= 1.0.2)
13
+ i18n (>= 0.7, < 2)
14
+ minitest (~> 5.1)
15
+ tzinfo (~> 1.1)
16
+ ast (2.4.0)
17
+ case_transform (0.2)
18
+ activesupport
19
+ coderay (1.1.2)
20
+ concurrent-ruby (1.1.5)
21
+ diff-lcs (1.3)
22
+ i18n (1.6.0)
23
+ concurrent-ruby (~> 1.0)
24
+ jaro_winkler (1.5.2)
25
+ method_source (0.9.2)
26
+ minitest (5.11.3)
27
+ parallel (1.17.0)
28
+ parser (2.6.3.0)
29
+ ast (~> 2.4.0)
30
+ pry (0.12.2)
31
+ coderay (~> 1.1.0)
32
+ method_source (~> 0.9.0)
33
+ rainbow (3.0.0)
34
+ rspec (3.8.0)
35
+ rspec-core (~> 3.8.0)
36
+ rspec-expectations (~> 3.8.0)
37
+ rspec-mocks (~> 3.8.0)
38
+ rspec-core (3.8.0)
39
+ rspec-support (~> 3.8.0)
40
+ rspec-expectations (3.8.3)
41
+ diff-lcs (>= 1.2.0, < 2.0)
42
+ rspec-support (~> 3.8.0)
43
+ rspec-mocks (3.8.0)
44
+ diff-lcs (>= 1.2.0, < 2.0)
45
+ rspec-support (~> 3.8.0)
46
+ rspec-support (3.8.0)
47
+ rubocop (0.69.0)
48
+ jaro_winkler (~> 1.5.1)
49
+ parallel (~> 1.10)
50
+ parser (>= 2.6)
51
+ rainbow (>= 2.2.2, < 4.0)
52
+ ruby-progressbar (~> 1.7)
53
+ unicode-display_width (>= 1.4.0, < 1.7)
54
+ ruby-progressbar (1.10.0)
55
+ thread_safe (0.3.6)
56
+ tzinfo (1.2.5)
57
+ thread_safe (~> 0.1)
58
+ unicode-display_width (1.6.0)
59
+
60
+ PLATFORMS
61
+ ruby
62
+
63
+ DEPENDENCIES
64
+ bundler
65
+ json_api_deserializer!
66
+ pry
67
+ rspec
68
+ rubocop
69
+
70
+ BUNDLED WITH
71
+ 2.0.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Nick Palaniuk
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,59 @@
1
+ # Json Api Deserializer
2
+
3
+ > This is the deserializer code from [ActiveModelSerializers](https://github.com/rails-api/active_model_serializers) for the JSON API spec
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'json_api_deserializer'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install json_api_deserializer
20
+
21
+ ## API
22
+
23
+ `JsonApiDeserializer.parse({}, [options])`
24
+
25
+ options = `:only, :except, :keys, :polymorphic`
26
+
27
+ ## Usage
28
+
29
+ ```ruby
30
+ JsonApiDeserializer.parse({
31
+ 'data' => {
32
+ 'type' => 'photos',
33
+ 'id' => 'zorglub',
34
+ 'attributes' => {
35
+ 'title' => 'Ember Hamster',
36
+ 'src' => 'http://example.com/images/productivity.png'
37
+ }
38
+ })
39
+
40
+ => { title: 'Ember Hamster', src: 'http://example.com/images/productivity.png' }
41
+ ```
42
+
43
+ ```ruby
44
+ JsonApiDeserializer.parse({
45
+ 'data' => {
46
+ 'type' => 'photos',
47
+ 'id' => 'zorglub',
48
+ 'attributes' => {
49
+ 'title' => 'Ember Hamster',
50
+ 'src' => 'http://example.com/images/productivity.png'
51
+ }
52
+ }, only: [:title])
53
+
54
+ => { title: 'Ember Hamster' }
55
+ ```
56
+
57
+ ## Contributing
58
+
59
+ Bug reports and pull requests are welcome on GitHub at https://github.com/nikkypx/json_api_deserializer
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "json_api_deserializer"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,24 @@
1
+ lib = File.expand_path("../lib", __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require "json_api_deserializer/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "json_api_deserializer"
7
+ spec.version = JsonApiDeserializer::VERSION
8
+ spec.authors = ["Nicholas Palaniuk"]
9
+ spec.email = ["npalaniuk+github@gmail.com"]
10
+
11
+ spec.summary = %q{Deserializer for JSON API spec}
12
+ spec.description = %q{Deserializer for JSON API spec}
13
+ spec.homepage = "https://github.com/nikkypx/json_api_deserializer"
14
+
15
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
16
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
17
+ end
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_development_dependency "bundler"
21
+ spec.add_development_dependency "rspec"
22
+ spec.add_dependency "case_transform"
23
+ spec.add_dependency "activesupport"
24
+ end
@@ -0,0 +1,208 @@
1
+ require 'json_api_deserializer/version'
2
+ require 'active_support/all'
3
+ require 'case_transform'
4
+
5
+ module JsonApiDeserializer
6
+ InvalidDocument = Class.new(ArgumentError)
7
+
8
+ module_function
9
+
10
+ # Transform a JSON API document, containing a single data object,
11
+ # into a hash that is ready for ActiveRecord::Base.new() and such.
12
+ # Raises InvalidDocument if the payload is not properly formatted.
13
+ #
14
+ # @param [Hash|ActionController::Parameters] document
15
+ # @param [Hash] options
16
+ # only: Array of symbols of whitelisted fields.
17
+ # except: Array of symbols of blacklisted fields.
18
+ # keys: Hash of translated keys (e.g. :author => :user).
19
+ # polymorphic: Array of symbols of polymorphic fields.
20
+ # @return [Hash]
21
+ #
22
+ # @example
23
+ # document = {
24
+ # data: {
25
+ # id: 1,
26
+ # type: 'post',
27
+ # attributes: {
28
+ # title: 'Title 1',
29
+ # date: '2015-12-20'
30
+ # },
31
+ # associations: {
32
+ # author: {
33
+ # data: {
34
+ # type: 'user',
35
+ # id: 2
36
+ # }
37
+ # },
38
+ # second_author: {
39
+ # data: nil
40
+ # },
41
+ # comments: {
42
+ # data: [{
43
+ # type: 'comment',
44
+ # id: 3
45
+ # },{
46
+ # type: 'comment',
47
+ # id: 4
48
+ # }]
49
+ # }
50
+ # }
51
+ # }
52
+ # }
53
+ #
54
+ # parse(document) #=>
55
+ # # {
56
+ # # title: 'Title 1',
57
+ # # date: '2015-12-20',
58
+ # # author_id: 2,
59
+ # # second_author_id: nil
60
+ # # comment_ids: [3, 4]
61
+ # # }
62
+ #
63
+ # parse(document, only: [:title, :date, :author],
64
+ # keys: { date: :published_at },
65
+ # polymorphic: [:author]) #=>
66
+ # # {
67
+ # # title: 'Title 1',
68
+ # # published_at: '2015-12-20',
69
+ # # author_id: '2',
70
+ # # author_type: 'people'
71
+ # # }
72
+ #
73
+ def parse!(document, options = {})
74
+ parse(document, options) do |invalid_payload, reason|
75
+ fail InvalidDocument, "Invalid payload (#{reason}): #{invalid_payload}"
76
+ end
77
+ end
78
+
79
+ # Same as parse!, but returns an empty hash instead of raising InvalidDocument
80
+ # on invalid payloads.
81
+ def parse(document, options = {})
82
+ # document = document.dup.permit!.to_h if document.is_a?(ActionController::Parameters)
83
+
84
+ validate_payload(document) do |invalid_document, reason|
85
+ yield invalid_document, reason if block_given?
86
+ return {}
87
+ end
88
+
89
+ primary_data = document['data']
90
+ attributes = primary_data['attributes'] || {}
91
+ attributes['id'] = primary_data['id'] if primary_data['id']
92
+ relationships = primary_data['relationships'] || {}
93
+
94
+ filter_fields(attributes, options)
95
+ filter_fields(relationships, options)
96
+
97
+ hash = {}
98
+ hash.merge!(parse_attributes(attributes, options))
99
+ hash.merge!(parse_relationships(relationships, options))
100
+
101
+ hash
102
+ end
103
+
104
+ # Checks whether a payload is compliant with the JSON API spec.
105
+ #
106
+ # @api private
107
+ # rubocop:disable Metrics/CyclomaticComplexity
108
+ def validate_payload(payload)
109
+ unless payload.is_a?(Hash)
110
+ yield payload, 'Expected hash'
111
+ return
112
+ end
113
+
114
+ primary_data = payload['data']
115
+ unless primary_data.is_a?(Hash)
116
+ yield payload, { data: 'Expected hash' }
117
+ return
118
+ end
119
+
120
+ attributes = primary_data['attributes'] || {}
121
+ unless attributes.is_a?(Hash)
122
+ yield payload, { data: { attributes: 'Expected hash or nil' } }
123
+ return
124
+ end
125
+
126
+ relationships = primary_data['relationships'] || {}
127
+ unless relationships.is_a?(Hash)
128
+ yield payload, { data: { relationships: 'Expected hash or nil' } }
129
+ return
130
+ end
131
+
132
+ relationships.each do |(key, value)|
133
+ unless value.is_a?(Hash) && value.key?('data')
134
+ yield payload, { data: { relationships: { key => 'Expected hash with :data key' } } }
135
+ end
136
+ end
137
+ end
138
+ # rubocop:enable Metrics/CyclomaticComplexity
139
+
140
+ # @api private
141
+ def filter_fields(fields, options)
142
+ if (only = options[:only])
143
+ fields.slice!(*Array(only).map(&:to_s))
144
+ elsif (except = options[:except])
145
+ fields.except!(*Array(except).map(&:to_s))
146
+ end
147
+ end
148
+
149
+ # @api private
150
+ def field_key(field, options)
151
+ (options[:keys] || {}).fetch(field.to_sym, field).to_sym
152
+ end
153
+
154
+ # @api private
155
+ def parse_attributes(attributes, options)
156
+ transform_keys(attributes, options)
157
+ .map { |(k, v)| { field_key(k, options) => v } }
158
+ .reduce({}, :merge)
159
+ end
160
+
161
+ # Given an association name, and a relationship data attribute, build a hash
162
+ # mapping the corresponding ActiveRecord attribute to the corresponding value.
163
+ #
164
+ # @example
165
+ # parse_relationship(:comments, [{ 'id' => '1', 'type' => 'comments' },
166
+ # { 'id' => '2', 'type' => 'comments' }],
167
+ # {})
168
+ # # => { :comment_ids => ['1', '2'] }
169
+ # parse_relationship(:author, { 'id' => '1', 'type' => 'users' }, {})
170
+ # # => { :author_id => '1' }
171
+ # parse_relationship(:author, nil, {})
172
+ # # => { :author_id => nil }
173
+ # @param [Symbol] assoc_name
174
+ # @param [Hash] assoc_data
175
+ # @param [Hash] options
176
+ # @return [Hash{Symbol, Object}]
177
+ #
178
+ # @api private
179
+ def parse_relationship(assoc_name, assoc_data, options)
180
+ prefix_key = field_key(assoc_name, options).to_s.singularize
181
+ hash =
182
+ if assoc_data.is_a?(Array)
183
+ { "#{prefix_key}_ids".to_sym => assoc_data.map { |ri| ri['id'] } }
184
+ else
185
+ { "#{prefix_key}_id".to_sym => assoc_data ? assoc_data['id'] : nil }
186
+ end
187
+
188
+ polymorphic = (options[:polymorphic] || []).include?(assoc_name.to_sym)
189
+ if polymorphic
190
+ hash["#{prefix_key}_type".to_sym] = assoc_data.present? ? assoc_data['type'].classify : nil
191
+ end
192
+
193
+ hash
194
+ end
195
+
196
+ # @api private
197
+ def parse_relationships(relationships, options)
198
+ transform_keys(relationships, options)
199
+ .map { |(k, v)| parse_relationship(k, v['data'], options) }
200
+ .reduce({}, :merge)
201
+ end
202
+
203
+ # @api private
204
+ def transform_keys(hash, options)
205
+ transform = options[:key_transform] || :underscore
206
+ CaseTransform.send(transform, hash)
207
+ end
208
+ end
@@ -0,0 +1,3 @@
1
+ module JsonApiDeserializer
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,111 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: json_api_deserializer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nicholas Palaniuk
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2019-05-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: case_transform
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: activesupport
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: Deserializer for JSON API spec
70
+ email:
71
+ - npalaniuk+github@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - ".travis.yml"
79
+ - Gemfile
80
+ - Gemfile.lock
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - bin/console
85
+ - bin/setup
86
+ - json_api_deserializer.gemspec
87
+ - lib/json_api_deserializer.rb
88
+ - lib/json_api_deserializer/version.rb
89
+ homepage: https://github.com/nikkypx/json_api_deserializer
90
+ licenses: []
91
+ metadata: {}
92
+ post_install_message:
93
+ rdoc_options: []
94
+ require_paths:
95
+ - lib
96
+ required_ruby_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ required_rubygems_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ requirements: []
107
+ rubygems_version: 3.0.3
108
+ signing_key:
109
+ specification_version: 4
110
+ summary: Deserializer for JSON API spec
111
+ test_files: []