如何通过 Apollo Client 在 NodeJS 中进行 GraphQL 订阅?

AUs*_*ser 6 node.js apollo graphql graphql-subscriptions apollo-client

我想订阅 GraphQL 服务器。该应用程序在 NodeJS 脚本中运行(即不在网络浏览器中)。

这是我目前所做的:

const fetch = require("node-fetch").default;
const apollo = require("apollo-boost");
const ApolloClient = apollo.default;
const { gql } = require("apollo-server");

const apolloClient = new ApolloClient({
  uri: "http://localhost:4000/graphql",
  fetch
});

apolloClient.subscribe({
  query: gql`
    subscription {
      startTaskRequested {
        pkRobot
        taskName
      }
    }
  `,
}).subscribe({
  next(x) { console.log(x) },
  error(err) { console.log(`Finished with error: ${ err }`) },
  complete() { console.log('Finished') }
});
Run Code Online (Sandbox Code Playgroud)

结果输出是:

{ data: { startTaskRequested: null } }
Finished
Run Code Online (Sandbox Code Playgroud)

在 GraphQL Server 上,我可以看到相应的解析器从未被调用。

如果我使用 Apollo 的 Playground 进行相同的订阅查询,则订阅有效并且我得到了我期望的结果:Apollo Playground

我已经为此奋斗了好几个小时,如果有人能指出我正确的方向,我将不胜感激。

AUs*_*ser 4

好吧,同时我发现了一个很棒的 github 存储库,其中包含我的问题的答案: https: //github.com/hasura/nodejs-graphql-subscriptions-boilerplate

我仍然不确定为什么我上面的代码会以这种方式运行。如果有人能够解释这一点,我将不胜感激:-)。