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

13
最近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仅适用于Apollo Client React集成。在VanillaJS中,有一个watchQuery,但声明它不应该用于订阅。还有一个subscribe可能是我正在寻找的,但没有文档记录。

是否有使用Apollo GraphQL客户端处理订阅的方法,而不需要在React组件内部?

1个回答

24

原来是通过subscribe方法实现的。我在这里找到了一个描述:https://dev-blog.apollodata.com/graphql-subscriptions-in-apollo-client-9a2457f015fb#eeba

ApolloClient.subscribe方法需要传入查询和变量,并返回一个observable对象。然后我们调用observable对象上的subscribe方法,并提供一个next函数,该函数将调用updateQuery方法。updateQuery方法指定了当给定订阅结果时,我们想要如何更新查询结果。

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); },
  });
}

2
客户端订阅的API真的很难找到。我正在使用react-apollo 2.5.5,现在似乎语法已经改变为next({ data })。然而,您不会像使用“Subscription”组件时那样获得任何“loading”状态。 - Paul Razvan Berg
这里的 data 是什么? - Amanda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接