I am getting the following response when doing submitting a subscription in Apollo Studio and I am loosing my mind debugging! I can't seem to find the problem.
Usually everything would work when doing server.installSubscriptionHandlers()
but now in Apollo version 3, according to the Documentation, things have to be done differently.
Read more here: https://www.apollographql.com/docs/apollo-server/data/subscriptions/
My Packages:
"graphql-subscriptions": "^2.0.0",
"graphql-tools": "^4.0.8",
"subscriptions-transport-ws": "^0.11.0",
"apollo-server-express": "^3.5.0",
"express": "^4.17.2",
Response in ApolloStudio:
{
"errors": [
{
"message": "Cannot read properties of undefined (reading 'asyncIterator')",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"newTodo"
]
}
]
}
What I typed into ApolloStudio:
subscription {
newTodo {
description
id
title
}
}
My relevant resolver code:
const NEW_TODO = "NEW_TODO";
const resolvers: IResolvers = {
//...
Mutation: {
addTodo: async (
parent,
args: null,
{ pubsub },
info: any
): Promise<Todo> => {
const newTodo: Todo = {
id: v4(),
title: "New Todo!",
description: "New Todo, Wohoo"
}
todos.push(newTodo);
pubsub.publish(NEW_TODO, { newTodo });
return todos[todos.length - 1];
}
},
Subscription: {
newTodo: {
subscribe: (_, __, {pubsub}) => pubsub.asyncIterator(NEW_TODO),
},
}
}
My Typedef:
type Subscription {
newTodo: Todo!
}
My Server:
//...
const pubsub = new PubSub();
const apolloServer = new ApolloServer({
schema,
context: ({req, res}): any => ({req, res, pubsub}),
plugins: [{
serverWillStart: async () => {
return {
async drainServer() {
subscriptionServer.close();
}
}
}
}],
});
(async function() {
await apolloServer.start();
apolloServer.applyMiddleware({ app, cors: true });
})();
const httpServer = createServer(app);
const subscriptionServer = new SubscriptionServer({
schema,
execute,
subscribe,
onConnect() {
console.log("SubscriptionServer ready!");
},
}, {
server: httpServer,
path: "/graphql"
});
//...
As @Jared Smith said, there was a Problem with subscribe()
not receiving pubsub
, so I kinda hacked something together by going to the server code and changing const pubsub
to export const pubsub
and I imported it into the resolvers. Seems like an unelegant solution but it does the job for now!