[英]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特定于Apollo Client React集成。 在VanillaJS中有一个watchQuery,但它声明它不应该用于订阅。 还有一个订阅可能是我正在搜索的,但没有记录。
有没有办法使用Apollo GraphQL客户端处理订阅,而不是在React组件内?
原来它是订阅方法。 我在这里找到了一个描述: https : //dev-blog.apollodata.com/graphql-subscriptions-in-apollo-client-9a2457f015fb#eeba
ApolloClient.subscribe接受查询和变量,并返回一个observable。 然后我们在observable上调用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); },
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.