订阅未使用ApolloServer连接

时间:2018-11-21 15:25:00

标签: javascript graphql apollo-server graphql-subscriptions

我正在尝试建立订阅并使用ApolloServer(v 2.2.2)。我的安装程序突然突然停止工作。当我尝试连接到graphiql / Playground中的订阅时,出现错误消息:

{
  "error": "Could not connect to websocket endpoint ws://localhost:4000/graphql. Please check if the endpoint url is correct."
}

因为我的应用程序中有休息端点,所以我需要表达自己的观点,但我无法从下面的运行中得到最小的例子:

import http from 'http';
import { ApolloServer, PubSub } from 'apollo-server-express';
import express from 'express';

const pubsub = new PubSub();

// The DB
const messages = [];

const typeDefs = `
type Query {
  messages: [String!]!
}
type Mutation {
  addMessage(message: String!): [String!]!
}
type Subscription {
  newMessage: String!
}

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}
`;

const resolvers = {
  Query: {
    messages() {
      return messages;
    }
  },
  Mutation: {
    addMessage(root, { message }) {
      let entry = JSON.stringify({ id: messages.length, message: message });
      messages.push(entry);
      pubsub.publish('newMessage', { entry: entry });
      return messages;
    },
  },
  Subscription: {
    newMessage: {
      resolve: (message) => {
        return message.entry;
      },
      subscribe: () => pubsub.asyncIterator('newMessage'),
    },
  },
};

const app = express();

const PORT = 4000;

const server = new ApolloServer({
  typeDefs,
  resolvers,
  subscriptions: {
    onConnect: () => console.log('Connected to websocket'),
  }
});

server.applyMiddleware({ app })

const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

httpServer.listen(PORT, () => {
  console.log(` Server ready at http://localhost:${PORT}${server.graphqlPath}`)
  console.log(` Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
})

其他端点工作正常,但无法创建WebSocket。据我了解,我不必使用其他服务器或端口(请参见https://www.ably.io/concepts/websockets)。我已经修改过SubsciptionServer,但这应该由installSubscriptionHandlershere's the code)处理。

2 个答案:

答案 0 :(得分:0)

不知道问题出在什么地方,但是在更换计算机后它可以工作。

我创建了一个示例存储库:https://github.com/gforge/subscription_example,它既可以单独使用,也可以与Docker容器一起使用。

答案 1 :(得分:0)

很多时间过去了,现在我遇到了同样的问题,我找到了解决方案。

import { createServer } from 'http';
const app = express();
const server = new ApolloServer({});
server.applyMiddleware({ app });
const httpServer = createServer(app);
server.installSubscriptionHandlers(httpServer);
server.listen()

对我有用