Skip to content

Commit

Permalink
feat: add before_sideload hook (#371)
Browse files Browse the repository at this point in the history
* Add before_sideload hook to allow restoration of global state in sideload threads, .e.g. setting current tenant for sideloads

Co-authored-by: Jeff Keen <[email protected]>
  • Loading branch information
jhnvz and jkeen authored Mar 18, 2024
1 parent 689aac7 commit f68b61f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/graphiti/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Configuration
attr_accessor :pagination_links
attr_accessor :typecast_reads
attr_accessor :raise_on_missing_sidepost
attr_accessor :before_sideload

attr_reader :debug, :debug_models

Expand Down
1 change: 1 addition & 0 deletions lib/graphiti/scope.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def resolve_sideloads(results)
parent_resource = @resource
graphiti_context = Graphiti.context
resolve_sideload = -> {
Graphiti.config.before_sideload&.call(graphiti_context)
Graphiti.context = graphiti_context
sideload.resolve(results, q, parent_resource)
@resource.adapter.close if concurrent
Expand Down
10 changes: 10 additions & 0 deletions spec/scope_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,24 @@
end

context "with concurrency" do
let(:before_sideload) { double("BeforeSideload", call: nil) }

before { allow(Graphiti.config).to receive(:concurrency).and_return(true) }
before { allow(Graphiti.config).to receive(:before_sideload).and_return(before_sideload) }

it "closes db connections" do
allow(sideload).to receive(:resolve).and_return(sideload)

expect(resource.adapter).to receive(:close)
instance.resolve_sideloads(results)
end

it "calls configiration.before_sideload with context" do
Graphiti.context[:tenant_id] = 1
allow(sideload).to receive(:resolve).and_return(sideload)
expect(before_sideload).to receive(:call).with(hash_including(tenant_id: 1))
instance.resolve_sideloads(results)
end
end

context "without concurrency" do
Expand Down

0 comments on commit f68b61f

Please sign in to comment.