[英]How to trigger an apollo graphql subscription immediately?
I have a project setup with Apollo Server and Node.js. 我使用Apollo Server和Node.js进行了项目设置。 The following code listens for changes in the posts using a pubsub pattern and triggers the graphql subscription when their is a 'POSTS_CHANGED' pubsub.publish event.
以下代码使用pubsub模式侦听帖子中的更改,并在它们为'POSTS_CHANGED'pubsub.publish事件时触发graphql订阅。 I used the setInterval timer for demonstration purposes.
我将setInterval计时器用于演示目的。
I want to trigger the subscription just when a client is connected. 我想仅在连接客户端时触发订阅。 That is to fetch the posts when he/she loads the page.
那是他/她加载页面时获取帖子。 But I can't figure out a way to do it.
但是我想不出办法。
const { ApolloServer, PubSub, gql } = require('apollo-server')
const pubsub = new PubSub();
setInterval(async () => {
pubsub.publish('POSTS_CHANGED', { posts: [{title: 'title1', body: 'body1'}] })
}, 5*1000)
const typeDefs = gql`
type Post {
title: String
body: String
}
type Subscription {
posts: [Post]
}
`
const resolvers = {
Subscription: {
posts: {
subscribe: () => pubsub.asyncIterator(['POSTS_CHANGED']),
}
}
};
const apolloServer = new ApolloServer({ typeDefs, resolvers})
apolloServer.listen()
.then((connection) => {
console.log(`Apollo http running on ${connection.url}`)
console.log(`Apollo web sockets running on ${connection.subscriptionsUrl}`)
})
I want to avoid using a seperate Query to load the posts on page load to keep the project simple and clean, unless there is a serious reason to do so. 我要避免使用单独的Query来加载页面加载时的帖子,以保持项目的简洁明了,除非有严重的理由。
I Hope it may be help you.... 希望对您有所帮助。
you should use String value in asyncIterator
. 您应该在
asyncIterator
使用String值。
Subscription: {
posts: {
subscribe: () => pubsub.asyncIterator('POSTS_CHANGED'),
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.