Last active
January 8, 2025 00:07
-
-
Save rmosolgo/99877e18f3ea55db0aa09f8a2d1aeaae to your computer and use it in GitHub Desktop.
Removing unauthorized items from a connection in GraphQL-Ruby using scope_items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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