|
8 | 8 | superable_methods_source = superable_methods.map { |m| " #{m.inspect},\n" }.join |
9 | 9 | assert_includes trace_source, superable_methods_source |
10 | 10 | end |
| 11 | + |
| 12 | + |
| 13 | + describe "object hooks" do |
| 14 | + class ObjectHooksSchema < GraphQL::Schema |
| 15 | + class Thing < GraphQL::Schema::Object |
| 16 | + field :name, String |
| 17 | + end |
| 18 | + |
| 19 | + class Query < GraphQL::Schema::Object |
| 20 | + field :things, [Thing], resolve_static: true |
| 21 | + |
| 22 | + def self.things(context) |
| 23 | + [OpenStruct.new(name: "Thing One"), OpenStruct.new(name: "Thing Two")] |
| 24 | + end |
| 25 | + |
| 26 | + field :thing, Thing, resolve_static: true do |
| 27 | + argument :id, ID, loads: Thing, as: :thing |
| 28 | + end |
| 29 | + |
| 30 | + def self.thing(context, thing:) |
| 31 | + thing |
| 32 | + end |
| 33 | + |
| 34 | + field :thing_name, String, resolve_static: true do |
| 35 | + argument :thing_id, ID, loads: Thing |
| 36 | + end |
| 37 | + |
| 38 | + def self.thing_name(context, thing:) |
| 39 | + thing.name |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + query(Query) |
| 44 | + use GraphQL::Execution::Next |
| 45 | + |
| 46 | + def self.object_from_id(id, ctx) |
| 47 | + OpenStruct.new(name: "Thing ##{id}") |
| 48 | + end |
| 49 | + |
| 50 | + def self.resolve_type(abs_type, obj, ctx) |
| 51 | + Thing |
| 52 | + end |
| 53 | + |
| 54 | + module LogTrace |
| 55 | + def objects(type, objects, context) |
| 56 | + context[:log] ||= [] |
| 57 | + context[:log] << "#{objects.size} objects as #{type.graphql_name}" |
| 58 | + super |
| 59 | + end |
| 60 | + |
| 61 | + def object_loaded(argument_definition, object, context) |
| 62 | + context[:log] ||= [] |
| 63 | + context[:log] << "#{argument_definition.path} loaded #{object.class}" |
| 64 | + super |
| 65 | + end |
| 66 | + end |
| 67 | + |
| 68 | + trace_with(LogTrace) |
| 69 | + end |
| 70 | + |
| 71 | + it "calls hooks with errors encountered during execution" do |
| 72 | + res = ObjectHooksSchema.execute_next("{ things { name } }") |
| 73 | + assert_equal ["Thing One", "Thing Two"], res["data"]["things"].map { |t| t["name"] } |
| 74 | + assert_equal ["1 objects as Query", "2 objects as Thing"], res.context[:log] |
| 75 | + |
| 76 | + res = ObjectHooksSchema.execute_next("{ thing(id: \"5\") { name } }") |
| 77 | + assert_equal "Thing #5", res["data"]["thing"]["name"] |
| 78 | + assert_equal ["1 objects as Query", "Query.thing.id loaded OpenStruct", "1 objects as Thing"], res.context[:log] |
| 79 | + |
| 80 | + res = ObjectHooksSchema.execute_next("{ thingName(thingId: \"77\") }") |
| 81 | + assert_equal "Thing #77", res["data"]["thingName"] |
| 82 | + assert_equal ["1 objects as Query", "Query.thingName.thingId loaded OpenStruct"], res.context[:log] |
| 83 | + end |
| 84 | + end |
11 | 85 | end |
0 commit comments