Skip to content

Commit

Permalink
Raise an error if write_subscription is called twice
Browse files Browse the repository at this point in the history
  • Loading branch information
rmosolgo committed Dec 9, 2024
1 parent 2d0608e commit 2eb67ed
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/graphql/schema/subscription.rb
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,12 @@ def self.topic_for(arguments:, field:, scope:)
# later in execution.
# @return [void]
def write_subscription
@subscription_written = true
context.schema.subscriptions.write_subscription(context.query, [event])
if subscription_written?
raise GraphQL::Error, "`write_subscription` was called but `#{self.class}#subscription_written?` is already true. Remove a call to `write subscription`."
else
@subscription_written = true
context.schema.subscriptions.write_subscription(context.query, [event])
end
nil
end

Expand Down
16 changes: 16 additions & 0 deletions spec/graphql/schema/subscription_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,14 @@ def subscribe

class DirectWrite < ImplicitWrite
type String
def subscribe
write_subscription
super
end
end

class DirectWriteTwice < DirectWrite
type String
def subscribe
write_subscription
super
Expand All @@ -732,6 +739,8 @@ def subscribe
class Subscription < GraphQL::Schema::Object
field :direct, subscription: DirectWrite
field :implicit, subscription: ImplicitWrite
field :direct_twice, subscription: DirectWriteTwice
field :with_payload, subscription: DirectWriteWithPayload
end

use WriteCheckSubscriptions.new
Expand All @@ -751,5 +760,12 @@ class Subscription < GraphQL::Schema::Object
assert_equal [1], res.context[:written_events].map(&:size)
assert_equal false, res.context.namespace(:subscriptions)[:subscriptions].values.first.subscription_written?
end

it "raises if write_subscription is called twice" do
err = assert_raises GraphQL::Error do
DirectWriteSchema.execute("subscription { directTwice }")
end
assert_equal "`write_subscription` was called but `DirectWriteSchema::DirectWriteTwice#subscription_written?` is already true. Remove a call to `write subscription`.", err.message
end
end
end

0 comments on commit 2eb67ed

Please sign in to comment.