【问题标题】:How do I create a GraphQL subscription with Apollo Client in Vanilla JS如何在 Vanilla JS 中使用 Apollo 客户端创建 GraphQL 订阅
【发布时间】:2017-12-20 04:05:17
【问题描述】:

最近 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 组件中?

【问题讨论】:

    标签: javascript graphql apollo apollo-client


    【解决方案1】:

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

    ApolloClient.subscribe 接受一个查询和变量,并返回一个 observable。然后我们在 observable 上调用 subscribe,并给它一个调用 updateQuery 的 next 函数。 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); },
      });
    }
    

    【讨论】:

    • 客户端订阅的 API 真的很难找到。我正在使用 react-apollo 2.5.5,现在语法似乎已更改为 next({ data })。但是,您不会像使用 Subscription 组件那样获得任何“加载”状态。
    • 这里的data 是什么?
    猜你喜欢
    • 2020-08-27
    • 2022-12-12
    • 2019-01-14
    • 2019-01-18
    • 2020-08-02
    • 2019-05-18
    • 2018-12-10
    • 2020-06-28
    • 2018-12-30
    相关资源
    最近更新 更多