【发布时间】:2022-03-29 22:36:19
【问题描述】:
我在 Apollo Studio 中提交订阅时收到以下响应,但我正在迷失调试!我似乎找不到问题。
通常在执行server.installSubscriptionHandlers() 时一切都会正常工作,但现在在 Apollo 版本 3 中,根据文档,必须以不同的方式完成。
在这里阅读更多:https://www.apollographql.com/docs/apollo-server/data/subscriptions/
我的包裹:
"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",
ApolloStudio 中的响应:
{
"errors": [
{
"message": "Cannot read properties of undefined (reading 'asyncIterator')",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"newTodo"
]
}
]
}
我在 ApolloStudio 中输入的内容:
subscription {
newTodo {
description
id
title
}
}
我的相关解析器代码:
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),
},
}
}
我的 Typedef:
type Subscription {
newTodo: Todo!
}
我的服务器:
//...
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"
});
//...
【问题讨论】:
-
我不使用graphql,但
subscribe: (_, __, {pubsub}) => pubsub.asyncIterator(NEW_TODO),无疑是你的问题,你的回调没有传递你认为的东西。 -
好的,还是很有帮助的,谢谢@JaredSmith
-
@JaredSmith 兄弟你刚刚帮我解决了你是个天才,上帝保佑你兄弟。
-
很高兴你解决了!
标签: typescript graphql apollo apollo-server