我有一个非常简单的GRAPHQL服务器在尝试使订阅正常工作时遇到问题。 当用户登录时,使用pubsub订阅和发布事件。
登录后,突变成功完成,但相应的订阅返回“ null”
请参阅以下GraphQL Playground的屏幕截图:
Pubsub实例化:
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
}
解析器突变:
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
};
}
解析程序订阅:
userAdded: {
subscribe: () => pubsub.asyncIterator(USER_SIGNED_IN)
}
代码可在CodeSandBox上使用(似乎在使用codesandbox时订阅很快就会超时。我建议您下载代码,然后npm安装npm开始测试): CodeSandBox
感谢任何帮助。