sanger-jsonapi-resources 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE.txt +1 -1
  3. data/README.md +35 -12
  4. data/lib/bug_report_templates/rails_5_latest.rb +125 -0
  5. data/lib/bug_report_templates/rails_5_master.rb +140 -0
  6. data/lib/jsonapi/active_relation/adapters/join_left_active_record_adapter.rb +26 -0
  7. data/lib/jsonapi/active_relation/join_manager.rb +297 -0
  8. data/lib/jsonapi/active_relation_resource.rb +898 -0
  9. data/lib/jsonapi/acts_as_resource_controller.rb +130 -113
  10. data/lib/jsonapi/basic_resource.rb +1164 -0
  11. data/lib/jsonapi/cached_response_fragment.rb +129 -0
  12. data/lib/jsonapi/callbacks.rb +2 -0
  13. data/lib/jsonapi/compatibility_helper.rb +29 -0
  14. data/lib/jsonapi/compiled_json.rb +13 -1
  15. data/lib/jsonapi/configuration.rb +88 -21
  16. data/lib/jsonapi/error.rb +29 -0
  17. data/lib/jsonapi/error_codes.rb +4 -0
  18. data/lib/jsonapi/exceptions.rb +82 -50
  19. data/lib/jsonapi/formatter.rb +5 -3
  20. data/lib/jsonapi/include_directives.rb +22 -67
  21. data/lib/jsonapi/link_builder.rb +76 -80
  22. data/lib/jsonapi/mime_types.rb +6 -10
  23. data/lib/jsonapi/naive_cache.rb +2 -0
  24. data/lib/jsonapi/operation.rb +18 -5
  25. data/lib/jsonapi/operation_result.rb +76 -16
  26. data/lib/jsonapi/paginator.rb +2 -0
  27. data/lib/jsonapi/path.rb +45 -0
  28. data/lib/jsonapi/path_segment.rb +78 -0
  29. data/lib/jsonapi/processor.rb +193 -115
  30. data/lib/jsonapi/relationship.rb +145 -14
  31. data/lib/jsonapi/request.rb +734 -0
  32. data/lib/jsonapi/resource.rb +3 -1251
  33. data/lib/jsonapi/resource_controller.rb +2 -0
  34. data/lib/jsonapi/resource_controller_metal.rb +7 -1
  35. data/lib/jsonapi/resource_fragment.rb +56 -0
  36. data/lib/jsonapi/resource_identity.rb +44 -0
  37. data/lib/jsonapi/resource_serializer.rb +158 -284
  38. data/lib/jsonapi/resource_set.rb +196 -0
  39. data/lib/jsonapi/resource_tree.rb +236 -0
  40. data/lib/jsonapi/resources/railtie.rb +9 -0
  41. data/lib/jsonapi/resources/version.rb +1 -1
  42. data/lib/jsonapi/response_document.rb +107 -83
  43. data/lib/jsonapi/routing_ext.rb +50 -26
  44. data/lib/jsonapi-resources.rb +23 -5
  45. data/lib/tasks/check_upgrade.rake +52 -0
  46. metadata +43 -31
  47. data/lib/jsonapi/cached_resource_fragment.rb +0 -127
  48. data/lib/jsonapi/operation_dispatcher.rb +0 -88
  49. data/lib/jsonapi/operation_results.rb +0 -35
  50. data/lib/jsonapi/relationship_builder.rb +0 -167
  51. data/lib/jsonapi/request_parser.rb +0 -678
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b9bc1314c078c61f44653dd5aa8b24e271853bf8be84b5d41eced75795b56ad2
4
- data.tar.gz: deee25658162d4971d977153214a2373db3599708f4c69d94d8662a5f90cdcfd
3
+ metadata.gz: 650cd436866c1e2bd95395039f642430ac9d0f1742e16b6229e4ff6c02749194
4
+ data.tar.gz: 8617ac86f123744a591f9d669c91e09210ba86840448037d8e087be15a755296
5
5
  SHA512:
6
- metadata.gz: 24e0ea2c4aa90ceab8dd3b5a5f38a127566a1e8bc7b58d83b1e5f22a488df0f4bc1eeef8685a0fd60ff35efdbed68ca75be6d9b662f6a0da95fa150da783dadd
7
- data.tar.gz: baee2a71eff19ef87efc2e6223ae93b5d47e346859cf777bf197f377eefe5dda886627c2bfa65a90294dda427b8f3724580ed85e887a3ff0d19435c5b9a0aca0
6
+ metadata.gz: 9287ea3df53d25721525c1e98b49bcdca8d7c936ec7674b649324a41dcde991e9a2c80cb464d273150710ab9fcf3a758c890788136d4f667552f3e5f0951c655
7
+ data.tar.gz: d85e68eb490870d9adafa8af7d63d6b7413aeb2c03be43efb510a9d4171b13dab763faff29fcf1610e6ea4ff7dfa4ef72b0530a678ebd4421c56489bdf12a682
data/LICENSE.txt CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2014 Larry Gebhardt
1
+ Copyright (c) 2014-2021 Cerebris Corporation
2
2
 
3
3
  MIT License
4
4
 
data/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # JSONAPI::Resources [![Gem Version](https://badge.fury.io/rb/jsonapi-resources.svg)](https://badge.fury.io/rb/jsonapi-resources) [![Build Status](https://secure.travis-ci.org/cerebris/jsonapi-resources.svg?branch=beta)](http://travis-ci.org/cerebris/jsonapi-resources) [![Code Climate](https://codeclimate.com/github/cerebris/jsonapi-resources/badges/gpa.svg)](https://codeclimate.com/github/cerebris/jsonapi-resources)
1
+ # JSONAPI::Resources [![Gem Version](https://badge.fury.io/rb/jsonapi-resources.svg)](https://badge.fury.io/rb/jsonapi-resources) [![Build Status](https://secure.travis-ci.org/cerebris/jsonapi-resources.svg?branch=master)](http://travis-ci.org/cerebris/jsonapi-resources) [![Code Climate](https://codeclimate.com/github/cerebris/jsonapi-resources/badges/gpa.svg)](https://codeclimate.com/github/cerebris/jsonapi-resources)
2
2
 
3
3
  [![Join the chat at https://gitter.im/cerebris/jsonapi-resources](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/cerebris/jsonapi-resources?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4
4
 
@@ -8,12 +8,12 @@
8
8
  Like JSON:API itself, JR's design is focused on the resources served by an API. JR needs little more than a definition
9
9
  of your resources, including their attributes and relationships, to make your server compliant with JSON API.
10
10
 
11
- JR is designed to work with Rails 4.2+, and provides custom routes, controllers, and serializers. JR's resources may be
11
+ JR is designed to work with Rails 5.1+, and provides custom routes, controllers, and serializers. JR's resources may be
12
12
  backed by ActiveRecord models or by custom objects.
13
13
 
14
14
  ## Documentation
15
15
 
16
- Full documentation can be found at [http://jsonapi-resources.com](http://jsonapi-resources.com), including the [v0.9 beta Guide](http://jsonapi-resources.com/v0.9/guide/) specific to this version.
16
+ Full documentation can be found at [http://jsonapi-resources.com](http://jsonapi-resources.com), including the [v0.10 alpha Guide](http://jsonapi-resources.com/v0.10/guide/) specific to this version.
17
17
 
18
18
  ## Demo App
19
19
 
@@ -28,26 +28,49 @@ which *should* be compatible with JSON:API compliant server implementations such
28
28
 
29
29
  Add JR to your application's `Gemfile`:
30
30
 
31
- gem 'sanger-jsonapi-resources'
31
+ ```
32
+ gem 'jsonapi-resources'
33
+ ```
32
34
 
33
35
  And then execute:
34
36
 
35
- $ bundle
37
+ ```bash
38
+ bundle
39
+ ```
36
40
 
37
41
  Or install it yourself as:
38
42
 
39
- $ gem install sanger-jsonapi-resources
43
+ ```bash
44
+ gem install jsonapi-resources
45
+ ```
40
46
 
41
- **For further usage see the [v0.9 beta Guide](http://jsonapi-resources.com/v0.9/guide/)**
47
+ **For further usage see the [v0.10 alpha Guide](http://jsonapi-resources.com/v0.10/guide/)**
42
48
 
43
49
  ## Contributing
44
50
 
51
+ 1. Submit an issue describing any new features you wish it add or the bug you intend to fix
45
52
  1. Fork it ( http://github.com/cerebris/jsonapi-resources/fork )
46
- 2. Create your feature branch (`git checkout -b my-new-feature`)
47
- 3. Commit your changes (`git commit -am 'Add some feature'`)
48
- 4. Push to the branch (`git push origin my-new-feature`)
49
- 5. Create a new Pull Request
53
+ 1. Create your feature branch (`git checkout -b my-new-feature`)
54
+ 1. Run the full test suite (`rake test`)
55
+ 1. Fix any failing tests
56
+ 1. Commit your changes (`git commit -am 'Add some feature'`)
57
+ 1. Push to the branch (`git push origin my-new-feature`)
58
+ 1. Create a new Pull Request
59
+
60
+ ## Did you find a bug?
61
+
62
+ * **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/cerebris/jsonapi-resources/issues).
63
+
64
+ * If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/cerebris/jsonapi-resources/issues/new).
65
+ Be sure to include a **title and clear description**, as much relevant information as possible,
66
+ and a **code sample** or an **executable test case** demonstrating the expected behavior that is not occurring.
67
+
68
+ * If possible, use the relevant bug report templates to create the issue.
69
+ Simply copy the content of the appropriate template into a .rb file, make the necessary changes to demonstrate the issue,
70
+ and **paste the content into the issue description or attach as a file**:
71
+ * [**Rails 5** issues](https://github.com/cerebris/jsonapi-resources/blob/master/lib/bug_report_templates/rails_5_master.rb)
72
+
50
73
 
51
74
  ## License
52
75
 
53
- Copyright 2014-2016 Cerebris Corporation. MIT License (see LICENSE for details).
76
+ Copyright 2014-2021 Cerebris Corporation. MIT License (see LICENSE for details).
@@ -0,0 +1,125 @@
1
+ begin
2
+ require 'bundler/inline'
3
+ rescue LoadError => e
4
+ STDERR.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
5
+ raise e
6
+ end
7
+
8
+ gemfile(true) do
9
+ source 'https://rubygems.org'
10
+
11
+ gem 'rails', require: false
12
+ gem 'sqlite3', platform: :mri
13
+
14
+ gem 'activerecord-jdbcsqlite3-adapter',
15
+ git: 'https://github.com/jruby/activerecord-jdbc-adapter',
16
+ branch: 'rails-5',
17
+ platform: :jruby
18
+
19
+ gem 'jsonapi-resources', require: false
20
+ end
21
+
22
+ # prepare active_record database
23
+ require 'active_record'
24
+
25
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
26
+ ActiveRecord::Base.logger = Logger.new(STDOUT)
27
+
28
+ ActiveRecord::Schema.define do
29
+ # Add your schema here
30
+ create_table :your_models, force: true do |t|
31
+ t.string :name
32
+ end
33
+ end
34
+
35
+ # create models
36
+ class YourModel < ActiveRecord::Base
37
+ end
38
+
39
+ # prepare rails app
40
+ require 'action_controller/railtie'
41
+ # require 'action_view/railtie'
42
+ require 'jsonapi-resources'
43
+
44
+ class ApplicationController < ActionController::Base
45
+ end
46
+
47
+ # prepare jsonapi resources and controllers
48
+ class YourModelsController < ApplicationController
49
+ include JSONAPI::ActsAsResourceController
50
+ end
51
+
52
+ class YourModelResource < JSONAPI::Resource
53
+ attribute :name
54
+ filter :name
55
+ end
56
+
57
+ class TestApp < Rails::Application
58
+ config.root = File.dirname(__FILE__)
59
+ config.logger = Logger.new(STDOUT)
60
+ Rails.logger = config.logger
61
+
62
+ secrets.secret_token = 'secret_token'
63
+ secrets.secret_key_base = 'secret_key_base'
64
+
65
+ config.eager_load = false
66
+ end
67
+
68
+ # initialize app
69
+ Rails.application.initialize!
70
+
71
+ JSONAPI.configure do |config|
72
+ config.json_key_format = :underscored_key
73
+ config.route_format = :underscored_key
74
+ end
75
+
76
+ # draw routes
77
+ Rails.application.routes.draw do
78
+ jsonapi_resources :your_models, only: [:index, :create]
79
+ end
80
+
81
+ # prepare tests
82
+ require 'minitest/autorun'
83
+ require 'rack/test'
84
+
85
+ # Replace this with the code necessary to make your test fail.
86
+ class BugTest < Minitest::Test
87
+ include Rack::Test::Methods
88
+
89
+ def json_api_headers
90
+ {'Accept' => JSONAPI::MEDIA_TYPE, 'CONTENT_TYPE' => JSONAPI::MEDIA_TYPE}
91
+ end
92
+
93
+ def test_index_your_models
94
+ record = YourModel.create! name: 'John Doe'
95
+ get '/your_models', nil, json_api_headers
96
+ assert last_response.ok?
97
+ json_response = JSON.parse(last_response.body)
98
+ refute_nil json_response['data']
99
+ refute_empty json_response['data']
100
+ refute_empty json_response['data'].first
101
+ assert record.id.to_s, json_response['data'].first['id']
102
+ assert 'your_models', json_response['data'].first['type']
103
+ assert({'name' => 'John Doe'}, json_response['data'].first['attributes'])
104
+ end
105
+
106
+ def test_create_your_models
107
+ json_request = {
108
+ 'data' => {
109
+ type: 'your_models',
110
+ attributes: {
111
+ name: 'Jane Doe'
112
+ }
113
+ }
114
+ }
115
+ post '/your_models', json_request.to_json, json_api_headers
116
+ assert last_response.created?
117
+ refute_nil YourModel.find_by(name: 'Jane Doe')
118
+ end
119
+
120
+ private
121
+
122
+ def app
123
+ Rails.application
124
+ end
125
+ end
@@ -0,0 +1,140 @@
1
+ begin
2
+ require 'bundler/inline'
3
+ require 'bundler'
4
+ rescue LoadError => e
5
+ STDERR.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
6
+ raise e
7
+ end
8
+
9
+ gemfile(true, ui: ENV['SILENT'] ? Bundler::UI::Silent.new : Bundler::UI::Shell.new) do
10
+ source 'https://rubygems.org'
11
+
12
+ gem 'rails', require: false
13
+ gem 'sqlite3', platform: :mri
14
+
15
+ gem 'activerecord-jdbcsqlite3-adapter',
16
+ git: 'https://github.com/jruby/activerecord-jdbc-adapter',
17
+ branch: 'rails-5',
18
+ platform: :jruby
19
+
20
+ if ENV['JSONAPI_RESOURCES_PATH']
21
+ gem 'jsonapi-resources', path: ENV['JSONAPI_RESOURCES_PATH'], require: false
22
+ else
23
+ gem 'jsonapi-resources', git: 'https://github.com/cerebris/jsonapi-resources', require: false
24
+ end
25
+
26
+ end
27
+
28
+ # prepare active_record database
29
+ require 'active_record'
30
+
31
+ class NullLogger < Logger
32
+ def initialize(*_args)
33
+ end
34
+
35
+ def add(*_args, &_block)
36
+ end
37
+ end
38
+
39
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
40
+ ActiveRecord::Base.logger = ENV['SILENT'] ? NullLogger.new : Logger.new(STDOUT)
41
+ ActiveRecord::Migration.verbose = !ENV['SILENT']
42
+
43
+ ActiveRecord::Schema.define do
44
+ # Add your schema here
45
+ create_table :your_models, force: true do |t|
46
+ t.string :name
47
+ end
48
+ end
49
+
50
+ # create models
51
+ class YourModel < ActiveRecord::Base
52
+ end
53
+
54
+ # prepare rails app
55
+ require 'action_controller/railtie'
56
+ # require 'action_view/railtie'
57
+ require 'jsonapi-resources'
58
+
59
+ class ApplicationController < ActionController::Base
60
+ end
61
+
62
+ # prepare jsonapi resources and controllers
63
+ class YourModelsController < ApplicationController
64
+ include JSONAPI::ActsAsResourceController
65
+ end
66
+
67
+ class YourModelResource < JSONAPI::Resource
68
+ attribute :name
69
+ filter :name
70
+ end
71
+
72
+ class TestApp < Rails::Application
73
+ config.root = File.dirname(__FILE__)
74
+ config.logger = ENV['SILENT'] ? NullLogger.new : Logger.new(STDOUT)
75
+ Rails.logger = config.logger
76
+
77
+ secrets.secret_token = 'secret_token'
78
+ secrets.secret_key_base = 'secret_key_base'
79
+
80
+ config.eager_load = false
81
+ end
82
+
83
+ # initialize app
84
+ Rails.application.initialize!
85
+
86
+ JSONAPI.configure do |config|
87
+ config.json_key_format = :underscored_key
88
+ config.route_format = :underscored_key
89
+ end
90
+
91
+ # draw routes
92
+ Rails.application.routes.draw do
93
+ jsonapi_resources :your_models, only: [:index, :create]
94
+ end
95
+
96
+ # prepare tests
97
+ require 'minitest/autorun'
98
+ require 'rack/test'
99
+
100
+ # Replace this with the code necessary to make your test fail.
101
+ class BugTest < Minitest::Test
102
+ include Rack::Test::Methods
103
+
104
+ def json_api_headers
105
+ {'Accept' => JSONAPI::MEDIA_TYPE, 'CONTENT_TYPE' => JSONAPI::MEDIA_TYPE}
106
+ end
107
+
108
+ def test_index_your_models
109
+ record = YourModel.create! name: 'John Doe'
110
+ get '/your_models', nil, json_api_headers
111
+ assert last_response.ok?
112
+ json_response = JSON.parse(last_response.body)
113
+ refute_nil json_response['data']
114
+ refute_empty json_response['data']
115
+ refute_empty json_response['data'].first
116
+ assert record.id.to_s, json_response['data'].first['id']
117
+ assert 'your_models', json_response['data'].first['type']
118
+ assert({'name' => 'John Doe'}, json_response['data'].first['attributes'])
119
+ end
120
+
121
+ def test_create_your_models
122
+ json_request = {
123
+ 'data' => {
124
+ type: 'your_models',
125
+ attributes: {
126
+ name: 'Jane Doe'
127
+ }
128
+ }
129
+ }
130
+ post '/your_models', json_request.to_json, json_api_headers
131
+ assert last_response.created?
132
+ refute_nil YourModel.find_by(name: 'Jane Doe')
133
+ end
134
+
135
+ private
136
+
137
+ def app
138
+ Rails.application
139
+ end
140
+ end
@@ -0,0 +1,26 @@
1
+ module JSONAPI
2
+ module ActiveRelation
3
+ module Adapters
4
+ module JoinLeftActiveRecordAdapter
5
+ # Extends left_joins functionality to rails 4, and uses the same logic for rails 5.0.x and 5.1.x
6
+ # The default left_joins logic of rails 5.2.x is used. This results in and extra join in some cases. For
7
+ # example Post.joins(:comments).joins_left(comments: :author) will join the comments table twice,
8
+ # once inner and once left in 5.2, but only as inner in earlier versions.
9
+ def joins_left(*columns)
10
+ if Rails::VERSION::MAJOR >= 6 || (Rails::VERSION::MAJOR >= 5 && ActiveRecord::VERSION::MINOR >= 2)
11
+ left_joins(columns)
12
+ else
13
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(self, columns, [])
14
+ joins(join_dependency)
15
+ end
16
+ end
17
+
18
+ alias_method :join_left, :joins_left
19
+ end
20
+
21
+ if defined?(ActiveRecord)
22
+ ActiveRecord::Base.extend JoinLeftActiveRecordAdapter
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,297 @@
1
+ module JSONAPI
2
+ module ActiveRelation
3
+
4
+ # Stores relationship paths starting from the resource_klass, consolidating duplicate paths from
5
+ # relationships, filters and sorts. When joins are made the table aliases are tracked in join_details
6
+ class JoinManager
7
+ attr_reader :resource_klass,
8
+ :source_relationship,
9
+ :resource_join_tree,
10
+ :join_details
11
+
12
+ def initialize(resource_klass:,
13
+ source_relationship: nil,
14
+ relationships: nil,
15
+ filters: nil,
16
+ sort_criteria: nil)
17
+
18
+ @resource_klass = resource_klass
19
+ @join_details = nil
20
+ @collected_aliases = Set.new
21
+
22
+ @resource_join_tree = {
23
+ root: {
24
+ join_type: :root,
25
+ resource_klasses: {
26
+ resource_klass => {
27
+ relationships: {}
28
+ }
29
+ }
30
+ }
31
+ }
32
+ add_source_relationship(source_relationship)
33
+ add_sort_criteria(sort_criteria)
34
+ add_filters(filters)
35
+ add_relationships(relationships)
36
+ end
37
+
38
+ def join(records, options)
39
+ fail "can't be joined again" if @join_details
40
+ @join_details = {}
41
+ perform_joins(records, options)
42
+ end
43
+
44
+ # source details will only be on a relationship if the source_relationship is set
45
+ # this method gets the join details whether they are on a relationship or are just pseudo details for the base
46
+ # resource. Specify the resource type for polymorphic relationships
47
+ #
48
+ def source_join_details(type=nil)
49
+ if source_relationship
50
+ related_resource_klass = type ? resource_klass.resource_klass_for(type) : source_relationship.resource_klass
51
+ segment = PathSegment::Relationship.new(relationship: source_relationship, resource_klass: related_resource_klass)
52
+ details = @join_details[segment]
53
+ else
54
+ if type
55
+ details = @join_details["##{type}"]
56
+ else
57
+ details = @join_details['']
58
+ end
59
+ end
60
+ details
61
+ end
62
+
63
+ def join_details_by_polymorphic_relationship(relationship, type)
64
+ segment = PathSegment::Relationship.new(relationship: relationship, resource_klass: resource_klass.resource_klass_for(type))
65
+ @join_details[segment]
66
+ end
67
+
68
+ def join_details_by_relationship(relationship)
69
+ segment = PathSegment::Relationship.new(relationship: relationship, resource_klass: relationship.resource_klass)
70
+ @join_details[segment]
71
+ end
72
+
73
+ def self.get_join_arel_node(records, options = {})
74
+ init_join_sources = records.arel.join_sources
75
+ init_join_sources_length = init_join_sources.length
76
+
77
+ records = yield(records, options)
78
+
79
+ join_sources = records.arel.join_sources
80
+ if join_sources.length > init_join_sources_length
81
+ last_join = (join_sources - init_join_sources).last
82
+ else
83
+ # :nocov:
84
+ warn "get_join_arel_node: No join added"
85
+ last_join = nil
86
+ # :nocov:
87
+ end
88
+
89
+ return records, last_join
90
+ end
91
+
92
+ def self.alias_from_arel_node(node)
93
+ case node.left
94
+ when Arel::Table
95
+ node.left.name
96
+ when Arel::Nodes::TableAlias
97
+ node.left.right
98
+ when Arel::Nodes::StringJoin
99
+ # :nocov:
100
+ warn "alias_from_arel_node: Unsupported join type - use custom filtering and sorting"
101
+ nil
102
+ # :nocov:
103
+ end
104
+ end
105
+
106
+ private
107
+
108
+ def flatten_join_tree_by_depth(join_array = [], node = @resource_join_tree, level = 0)
109
+ join_array[level] = [] unless join_array[level]
110
+
111
+ node.each do |relationship, relationship_details|
112
+ relationship_details[:resource_klasses].each do |related_resource_klass, resource_details|
113
+ join_array[level] << { relationship: relationship,
114
+ relationship_details: relationship_details,
115
+ related_resource_klass: related_resource_klass}
116
+ flatten_join_tree_by_depth(join_array, resource_details[:relationships], level+1)
117
+ end
118
+ end
119
+ join_array
120
+ end
121
+
122
+ def add_join_details(join_key, details, check_for_duplicate_alias = true)
123
+ fail "details already set" if @join_details.has_key?(join_key)
124
+ @join_details[join_key] = details
125
+
126
+ # Joins are being tracked as they are added to the built up relation. If the same table is added to a
127
+ # relation more than once subsequent versions will be assigned an alias. Depending on the order the joins
128
+ # are made the computed aliases may change. The order this library performs the joins was chosen
129
+ # to prevent this. However if the relation is reordered it should result in reusing on of the earlier
130
+ # aliases (in this case a plain table name). The following check will catch this an raise an exception.
131
+ # An exception is appropriate because not using the correct alias could leak data due to filters and
132
+ # applied permissions being performed on the wrong data.
133
+ if check_for_duplicate_alias && @collected_aliases.include?(details[:alias])
134
+ fail "alias '#{details[:alias]}' has already been added. Possible relation reordering"
135
+ end
136
+
137
+ @collected_aliases << details[:alias]
138
+ end
139
+
140
+ def perform_joins(records, options)
141
+ join_array = flatten_join_tree_by_depth
142
+
143
+ join_array.each do |level_joins|
144
+ level_joins.each do |join_details|
145
+ relationship = join_details[:relationship]
146
+ relationship_details = join_details[:relationship_details]
147
+ related_resource_klass = join_details[:related_resource_klass]
148
+ join_type = relationship_details[:join_type]
149
+
150
+ if relationship == :root
151
+ unless source_relationship
152
+ add_join_details('', {alias: resource_klass._table_name, join_type: :root})
153
+ end
154
+ next
155
+ end
156
+
157
+ records, join_node = self.class.get_join_arel_node(records, options) {|records, options|
158
+ related_resource_klass.join_relationship(
159
+ records: records,
160
+ resource_type: related_resource_klass._type,
161
+ join_type: join_type,
162
+ relationship: relationship,
163
+ options: options)
164
+ }
165
+
166
+ details = {alias: self.class.alias_from_arel_node(join_node), join_type: join_type}
167
+
168
+ if relationship == source_relationship
169
+ if relationship.polymorphic? && relationship.belongs_to?
170
+ add_join_details("##{related_resource_klass._type}", details)
171
+ else
172
+ add_join_details('', details)
173
+ end
174
+ end
175
+
176
+ # We're adding the source alias with two keys. We only want the check for duplicate aliases once.
177
+ # See the note in `add_join_details`.
178
+ check_for_duplicate_alias = !(relationship == source_relationship)
179
+ add_join_details(PathSegment::Relationship.new(relationship: relationship, resource_klass: related_resource_klass), details, check_for_duplicate_alias)
180
+ end
181
+ end
182
+ records
183
+ end
184
+
185
+ def add_join(path, default_type = :inner, default_polymorphic_join_type = :left)
186
+ if source_relationship
187
+ if source_relationship.polymorphic?
188
+ # Polymorphic paths will come it with the resource_type as the first segment (for example `#documents.comments`)
189
+ # We just need to prepend the relationship portion the
190
+ sourced_path = "#{source_relationship.name}#{path}"
191
+ else
192
+ sourced_path = "#{source_relationship.name}.#{path}"
193
+ end
194
+ else
195
+ sourced_path = path
196
+ end
197
+
198
+ join_manager, _field = parse_path_to_tree(sourced_path, resource_klass, default_type, default_polymorphic_join_type)
199
+
200
+ @resource_join_tree[:root].deep_merge!(join_manager) { |key, val, other_val|
201
+ if key == :join_type
202
+ if val == other_val
203
+ val
204
+ else
205
+ :inner
206
+ end
207
+ end
208
+ }
209
+ end
210
+
211
+ def process_path_to_tree(path_segments, resource_klass, default_join_type, default_polymorphic_join_type)
212
+ node = {
213
+ resource_klasses: {
214
+ resource_klass => {
215
+ relationships: {}
216
+ }
217
+ }
218
+ }
219
+
220
+ segment = path_segments.shift
221
+
222
+ if segment.is_a?(PathSegment::Relationship)
223
+ node[:resource_klasses][resource_klass][:relationships][segment.relationship] ||= {}
224
+
225
+ # join polymorphic as left joins
226
+ node[:resource_klasses][resource_klass][:relationships][segment.relationship][:join_type] ||=
227
+ segment.relationship.polymorphic? ? default_polymorphic_join_type : default_join_type
228
+
229
+ segment.relationship.resource_types.each do |related_resource_type|
230
+ related_resource_klass = resource_klass.resource_klass_for(related_resource_type)
231
+
232
+ # If the resource type was specified in the path segment we want to only process the next segments for
233
+ # that resource type, otherwise process for all
234
+ process_all_types = !segment.path_specified_resource_klass?
235
+
236
+ if process_all_types || related_resource_klass == segment.resource_klass
237
+ related_resource_tree = process_path_to_tree(path_segments.dup, related_resource_klass, default_join_type, default_polymorphic_join_type)
238
+ node[:resource_klasses][resource_klass][:relationships][segment.relationship].deep_merge!(related_resource_tree)
239
+ end
240
+ end
241
+ end
242
+ node
243
+ end
244
+
245
+ def parse_path_to_tree(path_string, resource_klass, default_join_type = :inner, default_polymorphic_join_type = :left)
246
+ path = JSONAPI::Path.new(resource_klass: resource_klass, path_string: path_string)
247
+
248
+ field = path.segments[-1]
249
+ return process_path_to_tree(path.segments, resource_klass, default_join_type, default_polymorphic_join_type), field
250
+ end
251
+
252
+ def add_source_relationship(source_relationship)
253
+ @source_relationship = source_relationship
254
+
255
+ if @source_relationship
256
+ resource_klasses = {}
257
+ source_relationship.resource_types.each do |related_resource_type|
258
+ related_resource_klass = resource_klass.resource_klass_for(related_resource_type)
259
+ resource_klasses[related_resource_klass] = {relationships: {}}
260
+ end
261
+
262
+ join_type = source_relationship.polymorphic? ? :left : :inner
263
+
264
+ @resource_join_tree[:root][:resource_klasses][resource_klass][:relationships][@source_relationship] = {
265
+ source: true, resource_klasses: resource_klasses, join_type: join_type
266
+ }
267
+ end
268
+ end
269
+
270
+ def add_filters(filters)
271
+ return if filters.blank?
272
+ filters.each_key do |filter|
273
+ # Do not add joins for filters with an apply callable. This can be overridden by setting perform_joins to true
274
+ next if resource_klass._allowed_filters[filter].try(:[], :apply) &&
275
+ !resource_klass._allowed_filters[filter].try(:[], :perform_joins)
276
+
277
+ add_join(filter, :left)
278
+ end
279
+ end
280
+
281
+ def add_sort_criteria(sort_criteria)
282
+ return if sort_criteria.blank?
283
+
284
+ sort_criteria.each do |sort|
285
+ add_join(sort[:field], :left)
286
+ end
287
+ end
288
+
289
+ def add_relationships(relationships)
290
+ return if relationships.blank?
291
+ relationships.each do |relationship|
292
+ add_join(relationship, :left)
293
+ end
294
+ end
295
+ end
296
+ end
297
+ end