NestJS GraphQL 订阅不适用于“graphql-ws”

Beh*_*adV 12 graphql graphql-subscriptions nestjs

我正在尝试升级我们的 NestJS GraphQL 订阅服务器以利用graphql-ws而不是当前的subscriptions-transport-ws(如NestJS 文档所建议的)。我将NestJS版本升级到

    "@nestjs/core": "^8.0.6",
    "@nestjs/graphql": "^9.0.4",
    "@nestjs/platform-express": "^8.0.6",
    "graphql": "^15.5.3",
    "graphql-tools": "^8.2.0",
    "apollo-server-express": "^3.3.0",
Run Code Online (Sandbox Code Playgroud)

之后,我将subscriptions选项添加到App.Module

    GraphQLModule.forRoot({
      autoSchemaFile: true,
      sortSchema: true,
      playground: true,
      installSubscriptionHandlers: true,
      subscriptions: {
        'graphql-ws': true
      },
    }),
Run Code Online (Sandbox Code Playgroud)

但是,当我(在操场上)订阅以前有效的订阅时,我得到:

{
  "error": "Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct."
}
Run Code Online (Sandbox Code Playgroud)

在控制台中我得到:

WebSocket protocol error occured. It was most likely caused due to an unsupported subprotocol "graphql-ws" requested by the client. graphql-ws implements exclusively the "graphql-transport-ws" subprotocol, please make sure that the client implements it too.
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情:

  • 添加graphql-ws
  • 再次升级NestJS版本
  • installSubscriptionHandlers从配置中删除该选项
  • 设置graphql-ws配置而不是传递true
  • 使用WebSocket Test ClientGoogle Chrome 扩展程序而不是 Playground

但没有一个奏效。抱歉发了这么长的帖子。我怎样才能解决这个问题?

小智 13

在 Apollo Server 3 发布时,GraphQL Playground 或 Apollo Explorer 尚不支持 graphql-ws 库中使用的协议。

这里

仅当通过 Playground 与订阅交互对您来说没有多大用处,并且您可以仅从已设置为使用 graphql-ws 的自己的客户端与订阅交互时,才建议使用 graphql-ws。

设置您的客户端以将 graphql-ws 与 Apollo 结合使用。看这里


小智 12

这将完成这项工作:

subscriptions: {
    'graphql-ws': true,
    'subscriptions-transport-ws': true,
  },
Run Code Online (Sandbox Code Playgroud)

正如文档中提到的:

暗示

您还可以同时使用这两个包(subscriptions-transport-ws 和 graphql-ws),例如,为了向后兼容。