订阅 URL 在 Apollo Graphql 订阅服务器中不起作用

Subscription URL doesn't work in Apollo Graphql Subscription Server

我有一个 graphql 服务器使用 apollo-server-express。下面是一个基本的 graphql 请求响应模式的代码。

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ connection }) => {
    if (connection) {
      return {
        ...connection.context,
      };
    }
    return null;
  },
});

server.applyMiddleware({ app, path: '/graphql' });

它工作正常。你可以看到它使用 applyMiddleware 来使用快速服务器。我可以在 http://localhost:8080/graphql url 上打开 graphiql 并从那里进行测试。后来我在我的代码中添加了订阅支持:

const { SubscriptionServer } = require('subscriptions-transport-ws');
const { createServer } = require('http');
const ws = createServer(app);
SubscriptionServer.create({...}, {
    server: ws,
    path: '/subscriptions',
  });

完成后,我的应用程序功能正常运行,但我无法在 graphiql 游乐场上对其进行测试。它抱怨订阅 URL 总是 http://localhost:8080/graphql 而不是 http://localhost:8080/subscriptions

我发现有人说要用这个代码:

app.use(‘/graphiql’, graphiqlExpress({
  endpointURL: ‘/graphql’,
  subscriptionsEndpoint: `ws://localhost:3000/subscriptions`,
}));

但我的应用正在使用 applyMiddleware。我想知道如何让它在我的案例中发挥作用。

GraphQL Playground 端点的选项被传递给 ApolloServer 构造函数,如图 in the docs

const server = new ApolloServer({
  playground: {
    subscriptionEndpoint: 'your custom subscription endpoint',
    // other GraphQL Playground options
  },
  ...
});

显示可用选项 here