Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a GraphQL subscription with Apollo Client in Vanilla JS

Recently Apollo Client released a websocket subscription feature, but so far I've only seen it used by launching a query using subscribeToMore inside the componentWillMount lifecycle hook.

Here is an example taken from 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 subscribeToMore is specific to Apollo Client React integration. In VanillaJS there is a watchQuery, but it's stated it should not be used for subscriptions. There is also a subscribe that might be what I'm searching for, but is not documented.

Is there any way using Apollo GraphQL client to handle subscriptions, without being inside a React Component?

like image 953
xabitrigo Avatar asked Jul 15 '17 00:07

xabitrigo


People also ask

What is the difference between a GraphQL query and subscription?

Like queries, subscriptions enable you to fetch data. Unlike queries, subscriptions are long-lasting operations that can change their result over time. They can maintain an active connection to your GraphQL server (most commonly via WebSocket), enabling the server to push updates to the subscription's result.

Do you need Apollo server for GraphQL?

Unfortunately, while I'm sure their platform is great, if you're setting up a fresh GraphQL API you should not start with Apollo. It certainly might be useful later, but on day 1 it's a trap, and you'll make your life simpler and easier if you avoid it entirely.


1 Answers

Turns out it is the subscribe method. I found a description here: https://dev-blog.apollodata.com/graphql-subscriptions-in-apollo-client-9a2457f015fb#eeba

ApolloClient.subscribe takes a query and variables, and returns an observable. We then call subscribe on the observable, and give it a next function which will call updateQuery. updateQuery specifies how we want our query result to be updated when given the subscription result.

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); },
  });
}
like image 166
xabitrigo Avatar answered Sep 22 '22 12:09

xabitrigo