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

xab*_*igo 6 javascript apollo graphql apollo-client

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

这是取自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;
      }
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

但是subscribeToMore特定于Apollo Client React集成。在VanillaJS中,有一个watchQuery,但声明不应将其用于订阅。还有一个订阅可能是我要搜索的内容,但没有记录。

有什么方法可以使用Apollo GraphQL客户端来处理订阅,而无需在React组件内部?

xab*_*igo 10

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

ApolloClient.subscribe接受查询和变量,并返回一个可观察值。然后,我们在可观察对象上调用订阅,并为其提供下一个函数,该函数将调用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); },
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 客户端订阅的 API 真的很难找到。我正在使用 react-apollo 2.5.5,现在语法似乎已更改为 `next({ data })`。但是,您不会像使用“订阅”组件那样获得任何“加载”状态。 (2认同)