Skip to content

Commit 93ca329

Browse files
authored
Merge pull request rmosolgo#2350 from rmosolgo/fix-late-query-string-assignment
Fix late query string assignment
2 parents 1a21f66 + b036d49 commit 93ca329

File tree

2 files changed

+40
-7
lines changed

2 files changed

+40
-7
lines changed

lib/graphql/query.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,12 @@ def initialize(name)
4444

4545
# @return [GraphQL::Language::Nodes::Document]
4646
def document
47-
with_prepared_ast { @document }
47+
# It's ok if this hasn't been assigned yet
48+
if @query_string || @document
49+
with_prepared_ast { @document }
50+
else
51+
nil
52+
end
4853
end
4954

5055
def inspect

spec/graphql/execution/instrumentation_spec.rb

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,23 +62,45 @@ def after_query(query)
6262
end
6363
end
6464

65+
# This is how you might add queries from a persisted query backend
66+
67+
class QueryStringInstrumenter
68+
def before_query(query)
69+
if query.context[:extra_query_string] && query.query_string.nil?
70+
query.query_string = query.context[:extra_query_string]
71+
end
72+
end
73+
74+
def after_query(query)
75+
end
76+
end
77+
6578
let(:query_type) {
66-
GraphQL::ObjectType.define do
67-
name "Query"
68-
field :int, types.Int do
69-
argument :value, types.Int
70-
resolve ->(obj, args, ctx) { args.value }
79+
Class.new(GraphQL::Schema::Object) do
80+
graphql_name "Query"
81+
field :int, Integer, null: true do
82+
argument :value, Integer, required: false
83+
end
84+
85+
def int(value:)
86+
value
7187
end
7288
end
7389
}
7490

7591
let(:schema) {
7692
spec = self
77-
GraphQL::Schema.define do
93+
Class.new(GraphQL::Schema) do
7894
query(spec.query_type)
7995
instrument(:query, FirstInstrumenter.new)
8096
instrument(:query, SecondInstrumenter.new)
8197
instrument(:query, ExecutionErrorInstrumenter.new)
98+
instrument(:query, QueryStringInstrumenter.new)
99+
100+
if TESTING_INTERPRETER
101+
use GraphQL::Analysis::AST
102+
use GraphQL::Execution::Interpreter
103+
end
82104
end
83105
}
84106

@@ -114,6 +136,12 @@ def after_query(query)
114136
assert_equal "Raised from instrumenter before_query", res["errors"].first["message"]
115137
refute res.key?("data"), "The query doesn't run"
116138
end
139+
140+
it "can assign a query string there" do
141+
context = { extra_query_string: "{ __typename }"}
142+
res = schema.execute(nil, context: context)
143+
assert_equal "Query", res["data"]["__typename"]
144+
end
117145
end
118146

119147
describe "within a multiplex" do

0 commit comments

Comments
 (0)