简体   繁体   中英

How to trigger an apollo graphql subscription immediately?

I have a project setup with Apollo Server and 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. I used the setInterval timer for demonstration purposes.

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.

I Hope it may be help you....

you should use String value in asyncIterator .

Subscription: {
    posts: {
        subscribe: () => pubsub.asyncIterator('POSTS_CHANGED'),
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM