Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Last active January 8, 2025 00:07
Show Gist options
  • Save rmosolgo/99877e18f3ea55db0aa09f8a2d1aeaae to your computer and use it in GitHub Desktop.
Save rmosolgo/99877e18f3ea55db0aa09f8a2d1aeaae to your computer and use it in GitHub Desktop.
Removing unauthorized items from a connection in GraphQL-Ruby using scope_items
require "bundler/inline"
gemfile do
gem "graphql", "2.4.8"
end
THINGS = [
{ name: "Camcorder" },
{ name: "Magnifying Glass" },
{ name: "Disappearing Ink" },
{ name: "Secret Dossier" },
]
class MySchema < GraphQL::Schema
class Thing < GraphQL::Schema::Object
def self.scope_items(items, ctx)
items.select { |item| item[:name] != "Secret Dossier" }
end
field :name, String
end
class Query < GraphQL::Schema::Object
field :things, Thing.connection_type, fallback_value: THINGS
field :custom_things, Thing.connection_type, scope: false
def custom_things
filtered_things = Thing.scope_items(THINGS, context)
GraphQL::Pagination::ArrayConnection.new(filtered_things)
end
end
query(Query)
end
# Access via `nodes`
pp MySchema.execute("{ things { nodes { name } } }").to_h
# {"data" => {"things" => {"nodes" => [{"name" => "Camcorder"}, {"name" => "Magnifying Glass"}, {"name" => "Disappearing Ink"}]}}}
# Access via `edges { node }`
pp MySchema.execute("{ things { edges { node { name } } } }").to_h
# {"data" =>
# {"things" => {"edges" => [{"node" => {"name" => "Camcorder"}}, {"node" => {"name" => "Magnifying Glass"}}, {"node" => {"name" => "Disappearing Ink"}}]}}}
# Direct application for manual connections:
pp MySchema.execute("{ customThings { nodes { name } } }").to_h
# {"data" => {"customThings" => {"nodes" => [{"name" => "Camcorder"}, {"name" => "Magnifying Glass"}, {"name" => "Disappearing Ink"}]}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment