Skip to content

Commit

Permalink
Fix compatibility with GraphQL Interpreter and BatchLoader.for
Browse files Browse the repository at this point in the history
  • Loading branch information
exAspArk committed Apr 8, 2020
1 parent 4b7596a commit 3135a6e
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
20 changes: 17 additions & 3 deletions lib/batch_loader/graphql.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,29 @@ class BatchLoader
class GraphQL
def self.use(schema_definition)
schema_definition.lazy_resolve(BatchLoader::GraphQL, :sync)
# for graphql gem versions <= 1.8.6 which work with BatchLoader instead of BatchLoader::GraphQL
schema_definition.instrument(:field, self)

# in cases when BatchLoader is being used instead of BatchLoader::GraphQL
if schema_definition.respond_to?(:interpreter?) && schema_definition.interpreter?
schema_definition.tracer(self)
else
schema_definition.instrument(:field, self)
end
end

def self.trace(event, _data)
if event == 'execute_field'
result = yield
result.respond_to?(:__sync) ? wrap(result) : result
else
yield
end
end

def self.instrument(type, field)
old_resolve_proc = field.resolve_proc
new_resolve_proc = ->(object, arguments, context) do
result = old_resolve_proc.call(object, arguments, context)
result.respond_to?(:__sync) ? BatchLoader::GraphQL.wrap(result) : result
result.respond_to?(:__sync) ? wrap(result) : result
end

field.redefine { resolve(new_resolve_proc) }
Expand Down
9 changes: 9 additions & 0 deletions spec/fixtures/graphql_schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,13 @@ class GraphqlSchema < GraphQL::Schema
query QueryType
use BatchLoader::GraphQL
end

if defined?(GraphQL::Execution::Interpreter)
class GraphqlSchemaWithInterpreter < GraphQL::Schema
use GraphQL::Execution::Interpreter
use GraphQL::Analysis::AST
query QueryType
use BatchLoader::GraphQL
end
end
end
17 changes: 16 additions & 1 deletion spec/graphql_spec.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
require "spec_helper"

RSpec.describe 'GraphQL integration' do
after do
User.destroy_all
Post.destroy_all
end

it 'resolves BatchLoader fields lazily' do
test(GraphqlSchema)
end

if defined?(GraphqlSchemaWithInterpreter)
it 'resolves BatchLoader fields lazily with GraphQL Interpreter' do
test(GraphqlSchemaWithInterpreter)
end
end

def test(schema)
user1 = User.save(id: "1")
user2 = User.save(id: "2")
Post.save(user_id: user1.id)
Expand All @@ -17,7 +32,7 @@

expect(User).to receive(:where).with(id: ["1", "2"]).twice.and_call_original

result = GraphqlSchema.execute(query)
result = schema.execute(query)

expect(result['data']).to eq({
'posts' => [
Expand Down

0 comments on commit 3135a6e

Please sign in to comment.