Reputation: 85
This is a simple test for Subscription in my nestjs project with graphql, but I got the error: Cannot return null for non-nullable field Subscription
Here is the code:
//* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~~~~~~~~~ */
@Mutation((returns) => Boolean)
testSubscription() {
pubsub.publish('somethingOnTrack', {
somethingOnTrack: 'something',
});
return true;
}
@Subscription((returns) => String)
orderSubscription() {
return pubsub.asyncIterator('somethingOnTrack');
}
Here is the GraphQLModule in the app.module
in nestjs:
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: true,
subscriptions: {
'graphql-ws': true,
'subscriptions-transport-ws': true,
},
}),
it try to using graphql-ws
& subscriptions-transport-ws
Next, I test it in the graphql:
subscription {
orderSubscription
}
mutation {
testSubscription
}
The Mutation can get result as expected:
{
"data": {
"testSubscription": true
}
}
But the Subscription got the error:
{
"errors": [
{
"message": "Cannot return null for non-nullable field Subscription.orderSubscription.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"orderSubscription"
]
}
],
"data": null
}
Seems the subscription cannot get the payload from the pubsub.publish? Why I got this error?
Upvotes: 0
Views: 1633
Reputation: 85
Cz this is code first, just return the type String in Subscription seems not make any sense, Finally, add a output type dto:
import { Field, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class SubscriptionOutput {
@Field((type) => String)
somethingOnTrack: string;
}
And also add {resolve: ...} to the Subscription, seems it is the correct syntax?? Change the test Subscription to follow:
//* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~~~~~~~~~ */
@Mutation((returns) => Boolean)
testSubscription() {
this.pubsub.publish('somethingOnTrack', { somethingOnTrack: 'something' });
return true;
}
@Subscription((returns) => SubscriptionOutput, {
resolve: (payload) => payload,
})
orderSubscription() {
return this.pubsub.asyncIterator('somethingOnTrack');
}
Upvotes: 1