apollographql / graphql-subscriptions

:newspaper: A small module that implements GraphQL subscriptions for Node.js
MIT License
1.59k stars 133 forks source link

Why does .publish call have to include the top-level field? #123

Closed jedwards1211 closed 6 years ago

jedwards1211 commented 6 years ago

To correctly get data to a subscriber of the somethingChanged subscription, we have to do:

pubsub.publish(SOMETHING_CHANGED_TOPIC, { somethingChanged: { id: "123" }})

But this means that the code that publishes has to know that the subscription is at the somethingChanged field. I don't want my code for publishing to have to worry about that, I don't see why it should be necessary. Wouldn't it be better if we could just publish this and graphql-subscriptions would wrap it in { somethingChanged: ... } to send to the client?

pubsub.publish(SOMETHING_CHANGED_TOPIC, { id: "123" })
NeoPhi commented 6 years ago

Subscription query resolving uses the same semantics as a standard GraphQL query resolver. The default GraphQL field resolver is equivalent to return obj.fieldName. When an event is published the resolver associated with the subscription gets the published payload as obj. Unless you override the default resolver for the subscription it will try to find fieldName on the object and return that, hence the need for { fieldName: ... } to be on the published event. To override that behavior and treat the published payload as the root object you can add a resolve: obj => obj property to the subscription.

jedwards1211 commented 6 years ago

Oh, weird. Thanks for the tip, using resolve: obj => obj works!