最近 Apollo Client 发布了 websocket 订阅功能,但到目前为止我只看到它通过在 componentWillMount 生命周期钩子中使用 subscribeToMore 启动查询来使用。
这是一个来自的例子https://dev-blog.apollodata.com/tutorial-graphql-subscriptions-client-side-40e185e4be76#0a8f 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;
}
}
});
}
But 订阅更多 http://dev.apollodata.com/react/api-queries.html#graphql-query-data-subscribeToMore特定于 Apollo Client React 集成。在香草JS http://dev.apollodata.com/core/apollo-client-api.html有一个 watchQuery,但声明它不应该用于订阅。还有一个订阅 http://dev.apollodata.com/core/apollo-client-api.html#ObservableQuery%5C.subscribe这可能是我正在寻找的内容,但没有记录。
有没有办法使用 Apollo GraphQL 客户端来处理订阅,而无需在 React 组件内?