1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
# frozen_string_literal: true
require "spec_helper"
describe GraphQL::Dataloader::Source do
class FailsToLoadSource < GraphQL::Dataloader::Source
def fetch(keys)
dataloader.with(FailsToLoadSource).load_all(keys)
end
end
it "raises an error when it tries too many times to sync" do
dl = GraphQL::Dataloader.new
dl.append_job { dl.with(FailsToLoadSource).load(1) }
err = assert_raises RuntimeError do
dl.run
end
expected_message = "FailsToLoadSource#sync tried 1000 times to load pending keys ([1]), but they still weren't loaded. There is likely a circular dependency."
assert_equal expected_message, err.message
end
it "is pending when waiting for false and nil" do
dl = GraphQL::Dataloader.new
dl.with(FailsToLoadSource).request(nil)
source_cache = dl.instance_variable_get(:@source_cache)
assert source_cache[FailsToLoadSource][[{}]].pending?
end
class CustomKeySource < GraphQL::Dataloader::Source
def result_key_for(record)
record[:id]
end
def fetch(records)
records.map { |r| r[:value] * 10 }
end
end
it "uses a custom key when configured" do
values = nil
GraphQL::Dataloader.with_dataloading do |dl|
first_req = dl.with(CustomKeySource).request({ id: 1, value: 10 })
second_rec = dl.with(CustomKeySource).request({ id: 2, value: 20 })
third_rec = dl.with(CustomKeySource).request({id: 1, value: 30 })
values = [
first_req.load,
second_rec.load,
third_rec.load
]
end
# There wasn't a `300` because the third requested value was de-duped to the first one.
assert_equal [100, 200, 100], values
end
class NoDataloaderSchema < GraphQL::Schema
class ThingSource < GraphQL::Dataloader::Source
def fetch(ids)
ids.map { |id| { name: "Thing-#{id}" } }
end
end
class Thing < GraphQL::Schema::Object
field :name, String
end
class Query < GraphQL::Schema::Object
field :thing, Thing do
argument :id, ID
end
def thing(id:)
context.dataloader.with(ThingSource).load(id)
end
end
query(Query)
end
it "raises an error when used without a dataloader" do
err = assert_raises GraphQL::Error do
NoDataloaderSchema.execute("{ thing(id: 1) { name } }")
end
expected_message = "GraphQL::Dataloader is not running -- add `use GraphQL::Dataloader` to your schema to use Dataloader sources."
assert_equal expected_message, err.message
end
end
|