I have an issue with a very simple GRAPHQL server trying to make subscriptions work. Using pubsub to subscribe and publish an event when a user signs in.
On signing in, the mutation completes successfully, but the corresponding subscription returns "null"
See below screenshots from GraphQL Playground:
Pubsub instantiation:
const { PubSub } = require("apollo-server");
const pubsub = new PubSub();
const USER_SIGNED_IN = "USER_SIGNED_IN";
typedefs:
type User {
id: ID!
firstName: String!
lastName: String
email: String!
cell: String
}
type AuthPayload {
token: String
user: User
}
type Subscription {
userAdded: User
}
resolver-mutation:
signin: async (parent, args, context) => {
const user = users.find(user => user.email === args.email);
if (!user) {
throw new Error("No account found. Please sign up.");
}
const valid = await bcrypt.compare(args.password, user.password);
if (!valid) {
throw new Error("Invalid Password");
}
const token = jwt.sign(
{
userId: user.id
},
"secret!"
);
pubsub.publish(USER_SIGNED_IN, { user });
return {
user,
token
};
}
resolver-subscription:
userAdded: {
subscribe: () => pubsub.asyncIterator(USER_SIGNED_IN)
}
Code is available on CodeSandBox (Seems like subscription times out quickly when using codesandbox. I recommend you download the code and npm install the npm start to test): CodeSandBox
Appreciate any assistance.