当我在阿波罗工作室提交订阅时,我得到了以下响应,并且我正在失去我的思想调试!我似乎找不到问题。
通常情况下,当执行server.installSubscriptionHandlers()时,一切都会正常工作,但是现在在阿波罗版本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),
},
}
}我的提胡枝子f:
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"
});
//...发布于 2021-12-30 13:19:35
正如@Jared所说,subscribe()没有接收pubsub有一个问题,所以我通过转到服务器代码并将const pubsub更改为export const pubsub,并将其导入解析器,从而对一些东西进行了黑客攻击。似乎是一个不雅的解决方案,但它做了目前的工作!
发布于 2022-03-29 14:36:19
我通过使用useServer在websocket服务器上设置上下文来解决这个问题,似乎查询和变异与订阅有不同的上下文,下面是我的代码
(async () => {
const app = express();
const httpServer = createServer(app);
const pubsub = new PubSub();
app.use(cors());
const schema = makeExecutableSchema({ typeDefs, resolvers});
const wsServer = new WebSocketServer({
server: httpServer,
path: '/graphql',
})
const serverCleanup = useServer({
schema,
context: (ctx, msg, args) => ({ pubsub }), // <-- SOLVES IT
}, wsServer);
const apolloServer = new ApolloServer({
schema,
context: ({ req, res }: any) => ({req, res, pubsub}),
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer(){
await serverCleanup.dispose();
},
};
}
},
],
});
await apolloServer.start();
apolloServer.applyMiddleware({ app, cors: false });
httpServer.listen({ port: 8000 }, () => {
console.log(
` Query endpoint ready at http://localhost:8000${apolloServer.graphqlPath}`
);
console.log(
` Subscription endpoint ready at ws://localhost:8000${apolloServer.graphqlPath}`
);
});
})()https://stackoverflow.com/questions/70531989
复制相似问题