I'm following along with the book Learning GraphQL and I came across a problem when implementing subscriptions. A resolver for one of the fields of the object being sent to the subscription doesn't work when viewing it from a subscription, but strangely works for mutations and queries. The resolver in question looks like this:
Photo: {
postedBy: (parent, args, {db}) => db.collection('users').findOne({githubLogin: parent.userID})
}
When I make the following mutation, I receive postedBy back just fine:
mutation($input: PostPhotoInput!) {
postPhoto(input: $input) {
name
url
postedBy {
name
}
}
}
Same when I make a query that returns that type:
{
allPhotos {
name
postedBy {
name
}
}
}
But when I start the following subscription and make a mutation that it's listening for:
subscription {
newPhoto {
name
url
postedBy {
name
}
}
}
I get the error Cannot read property 'collection' of undefined. I don't get an error if I use the subscription without the postedBy field. I can only assume that the undefined object is db, which is passed in from the context. Why does this work with queries and mutations, but not subscriptions?
For more context, here's the resolver for the subscription:
Subscription: {
newPhoto: {
subscribe: () => pubsub.asyncIterator('photo-added')
}
}
and here's the resolver for the mutation that published the event the subscription is listening for:
async postPhoto(parent, {input}, {db, currentUser}) {
if (!currentUser)
throw new Error('Only an authorized user can post a photo');
const newPhoto = {
...input,
userID: currentUser.githubLogin,
created: new Date()
};
const {insertedId} = await db
.collection('photos')
.insertOne(newPhoto);
newPhoto.id = insertedId;
pubsub.publish('photo-added', {newPhoto});
return newPhoto;
}
I found out what was wrong. It turns out that instead of getting context from the context function that passed to the constructor of ApolloServer, subscriptions get their context from the onConnect function that gets passed to the constructor of SubscriptionServer as described in the docs.