Last active
May 16, 2024 21:01
-
-
Save rmosolgo/2d25ec6be3ad20476a978dcbc9eb46d1 to your computer and use it in GitHub Desktop.
GraphQL-Pro `@defer` on Fragments when context flag is present
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.2.0" | |
# or: gem "graphql", "~>1.13.0" | |
gem "graphql-batch", "0.6.0" | |
gem "graphql-pro", "~>1.27.0" | |
end | |
class Schema < GraphQL::Schema | |
class Issue < GraphQL::Schema::Object | |
field :title, String | |
field :body, String | |
end | |
class Query < GraphQL::Schema::Object | |
field :issue, Issue | |
def issue | |
{ | |
title: "Failed Reticulated Splines", | |
body: "It encountered an error while reticulating splines" | |
} | |
end | |
end | |
class Defer < GraphQL::Pro::Defer | |
def self.resolve(obj, arguments, context, &block) | |
# only use defer if the run_defer_directive flag is set on the context | |
if context[:run_defer_directive] | |
# While the query is running, store the batch executor to re-use later | |
context[:graphql_batch_executor] ||= GraphQL::Batch::Executor.current | |
super | |
else | |
yield | |
end | |
end | |
class Deferral < GraphQL::Pro::Defer::Deferral | |
def resolve | |
# Before calling the deferred execution, | |
# set GraphQL-Batch back up: | |
prev_executor = GraphQL::Batch::Executor.current | |
GraphQL::Batch::Executor.current ||= @context[:graphql_batch_executor] | |
super | |
ensure | |
# Clean up afterward: | |
GraphQL::Batch::Executor.current = prev_executor | |
end | |
end | |
end | |
query(Query) | |
use Defer | |
end | |
query_str = <<-GRAPHQL | |
{ | |
issue { | |
title | |
... IssueBody @defer | |
} | |
} | |
fragment IssueBody on Issue { | |
body | |
} | |
GRAPHQL | |
res = Schema.execute(query_str, context: { run_defer_directive: true }) | |
res.context[:defer].each do |deferral| | |
pp [:deferred, deferral.to_h] | |
end | |
# [:deferred, {:hasNext=>true, :data=>{"issue"=>{"title"=>"Failed Reticulated Splines"}}}] | |
# [:deferred, {:path=>["issue"], :hasNext=>false, :data=>{"body"=>"It encountered an error while reticulating splines"}}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment