如何在 Vanilla JS 中使用 Apollo Client 创建 GraphQL 订阅

How do I create a GraphQL subscription with Apollo Client in Vanilla JS

最近 Apollo Client 发布了一个 websocket 订阅功能,但到目前为止我只看到它是通过在 componentWillMount 生命周期挂钩中使用 subscribeToMore 启动查询来使用的。

这是取自 https://dev-blog.apollodata.com/tutorial-graphql-subscriptions-client-side-40e185e4be76#0a8f

的示例
const messagesSubscription = gql`
  subscription messageAdded($channelId: ID!) {
    messageAdded(channelId: $channelId) {
      id
      text
    }
  }
`

componentWillMount() {
  this.props.data.subscribeToMore({
    document: messagesSubscription,
    variables: {
      channelId: this.props.match.params.channelId,
    },
    updateQuery: (prev, {subscriptionData}) => {
      if (!subscriptionData.data) {
        return prev;
      }
      const newMessage = subscriptionData.data.messageAdded;
      // don't double add the message
      if (!prev.channel.messages.find((msg) => msg.id === newMessage.id)) {
        return Object.assign({}, prev, {
          channel: Object.assign({}, prev.channel, {
            messages: [...prev.channel.messages, newMessage],
          })
        });
      } else {
        return prev;
      }
    }
  });
}

但是 subscribeToMore is specific to Apollo Client React integration. In VanillaJS there is a watchQuery, but it's stated it should not be used for subscriptions. There is also a subscribe 这可能是我要搜索的内容,但没有记录在案。

有没有办法使用 Apollo GraphQL 客户端来处理订阅,而不是在 React 组件中?

原来是订阅方法。我在这里找到了描述:https://dev-blog.apollodata.com/graphql-subscriptions-in-apollo-client-9a2457f015fb#eeba

ApolloClient.subscribe takes a query and variables, and returns an observable. We then call subscribe on the observable, and give it a next function which will call updateQuery. updateQuery specifies how we want our query result to be updated when given the subscription result.

subscribe(repoName, updateQuery){
  // call the "subscribe" method on Apollo Client
  this.subscriptionObserver = this.props.client.subscribe({
    query: SUBSCRIPTION_QUERY,
    variables: { repoFullName: repoName },
  }).subscribe({
    next(data) {
      // ... call updateQuery to integrate the new comment
      // into the existing list of comments
    },
    error(err) { console.error('err', err); },
  });
}