Skip to content

Commit

Permalink
Merge pull request #5157 from rmosolgo/visibility-top-level-caches
Browse files Browse the repository at this point in the history
Add top-level caches for Schema::Visibility
  • Loading branch information
rmosolgo authored Nov 11, 2024
2 parents a964042 + 08485eb commit 0b49803
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/graphql/schema/visibility.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ def profile_for(context, visibility_profile)
if @profiles.any?
if visibility_profile.nil?
if @dynamic
@schema.visibility_profile_class.new(context: context, schema: @schema)
if context.is_a?(Query::NullContext)
top_level_profile
else
@schema.visibility_profile_class.new(context: context, schema: @schema)
end
elsif @profiles.any?
raise ArgumentError, "#{@schema} expects a visibility profile, but `visibility_profile:` wasn't passed. Provide a `visibility_profile:` value or add `dynamic: true` to your visibility configuration."
end
Expand All @@ -121,13 +125,22 @@ def profile_for(context, visibility_profile)
else
@cached_profiles[visibility_profile] ||= @schema.visibility_profile_class.new(name: visibility_profile, context: context, schema: @schema)
end
elsif context.is_a?(Query::NullContext)
top_level_profile
else
@schema.visibility_profile_class.new(context: context, schema: @schema)
end
end

private

def top_level_profile(refresh: false)
if refresh
@top_level_profile = nil
end
@top_level_profile ||= @schema.visibility_profile_class.new(context: Query::NullContext.instance, schema: @schema)
end

def ensure_all_loaded(types_to_visit)
while (type = types_to_visit.shift)
if type.kind.fields? && @preloaded_types.add?(type)
Expand All @@ -137,6 +150,8 @@ def ensure_all_loaded(types_to_visit)
end
end
end
top_level_profile(refresh: true)
nil
end
end
end
Expand Down
12 changes: 12 additions & 0 deletions spec/graphql/schema/visibility_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,21 @@ class DynVisSchema < VisSchema
use GraphQL::Schema::Visibility, profiles: { public: {}, admin: {} }, dynamic: true, preload: false
end

class PreloadDynVisSchema < VisSchema
use GraphQL::Schema::Visibility, profiles: { public: {}, admin: {} }, dynamic: true, preload: true
end

def exec_query(...)
VisSchema.execute(...)
end

describe "top-level schema caches" do
it "re-uses results" do
assert_equal DynVisSchema.types.object_id, DynVisSchema.types.object_id
assert_equal PreloadDynVisSchema.types.object_id, PreloadDynVisSchema.types.object_id
end
end

describe "running queries" do
it "requires context[:visibility]" do
err = assert_raises ArgumentError do
Expand Down

0 comments on commit 0b49803

Please sign in to comment.