Skip to content

Commit 8479e13

Browse files
committed
Only allow object types to be union types, fixes #4243
1 parent 266aa76 commit 8479e13

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

lib/graphql/schema/union.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,18 @@ def assign_type_membership_object_type(object_type)
7070
private
7171

7272
def assert_valid_union_member(type_defn)
73-
if type_defn.is_a?(Module) && !type_defn.is_a?(Class)
73+
case type_defn
74+
when Class
75+
if !type_defn.kind.object?
76+
raise ArgumentError, "Union possible_types can only be object types (not #{type_defn.kind.name}, #{type_defn.inspect})"
77+
end
78+
when Module
7479
# it's an interface type, defined as a module
7580
raise ArgumentError, "Union possible_types can only be object types (not interface types), remove #{type_defn.graphql_name} (#{type_defn.inspect})"
81+
when String, GraphQL::Schema::LateBoundType
82+
# Ok - assume it will get checked later
83+
else
84+
raise ArgumentError, "Union possible_types can only be class-based GraphQL types (not #{type_defn.inspect} (#{type_defn.class.name}))."
7685
end
7786
end
7887
end

spec/graphql/schema/union_spec.rb

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,46 @@ def my_union
137137
end
138138
end
139139

140+
it "doesn't allow adding non-object types" do
141+
object_type = Class.new(GraphQL::Schema::Object) do
142+
graphql_name "SomeObject"
143+
end
144+
145+
err = assert_raises ArgumentError do
146+
Class.new(GraphQL::Schema::Union) do
147+
graphql_name "SomeUnion"
148+
possible_types object_type, GraphQL::Types::Int
149+
end
150+
end
151+
expected_message = "Union possible_types can only be object types (not SCALAR, "
152+
assert_includes err.message, expected_message
153+
154+
input_type = Class.new(GraphQL::Schema::InputObject) do
155+
graphql_name "SomeInput"
156+
argument :arg, GraphQL::Types::Int
157+
end
158+
159+
err = assert_raises ArgumentError do
160+
Class.new(GraphQL::Schema::Union) do
161+
graphql_name "SomeUnion"
162+
possible_types object_type, input_type
163+
end
164+
end
165+
166+
expected_message = "Union possible_types can only be object types (not INPUT_OBJECT, "
167+
assert_includes err.message, expected_message
168+
169+
err = assert_raises ArgumentError do
170+
Class.new(GraphQL::Schema::Union) do
171+
graphql_name "SomeUnion"
172+
possible_types object_type, 1234
173+
end
174+
end
175+
176+
expected_message = "Union possible_types can only be class-based GraphQL types (not 1234 (Integer))."
177+
assert_includes err.message, expected_message
178+
end
179+
140180
it "doesn't allow adding interface" do
141181
object_type = Class.new(GraphQL::Schema::Object) do
142182
graphql_name "SomeObject"

0 commit comments

Comments
 (0)