Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Created May 27, 2025 14:12
Show Gist options
  • Save rmosolgo/4c6c0a8f834e21ff2fd753ce90c19bd9 to your computer and use it in GitHub Desktop.
Save rmosolgo/4c6c0a8f834e21ff2fd753ce90c19bd9 to your computer and use it in GitHub Desktop.
Using a custom argument authentication option in GraphQL-Ruby
require "bundler/inline"
gemfile do
gem "graphql", "2.5.7"
end
class MySchema < GraphQL::Schema
class BaseArgument < GraphQL::Schema::Argument
def initialize(*args, authenticate_with: nil, **kwargs, &block)
@authenticate_with = authenticate_with
super(*args, **kwargs, &block)
end
def authorized?(obj, value, ctx)
self.loads.public_send(@authenticate_with, value) && super
end
end
class BaseField < GraphQL::Schema::Field
argument_class(BaseArgument)
end
class BaseObject < GraphQL::Schema::Object
field_class(BaseField)
end
class Thing < BaseObject
field :name, String
def self.top_secret?(thing)
thing[:name].include?("ABCD")
end
end
class Query < BaseObject
field :thing, Thing do
argument :id, ID, loads: Thing, authenticate_with: :top_secret?, as: :thing
end
def thing(thing:)
thing
end
end
def self.object_from_id(thing_id, ctx)
{ name: "Thing #{thing_id}"}
end
def self.resolve_type(abs_type, obj, ctx)
Thing
end
query(Query)
end
pp MySchema.execute("{ thing(id: \"ABCD\") { name } }").to_h
# {"data" => {"thing" => {"name" => "Thing ABCD"}}}
pp MySchema.execute("{ thing(id: \"HIJK\") { name } }").to_h
# This fails `.top_secret?`
# {"data" => {"thing" => nil}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment