Subscription

When we had initially set up Apollo with HttpLink. It supports queries and mutations but not subscriptions. So we have to install more dependencies to set up subscriptions.

React Apollo Subscriptions Setup

+ $ npm install subscriptions-transport-ws --save

Now we need to update our ApolloClient instance to point to the subscription server.

Open src/components/App.res and update the createApolloClient:

githubsrc/components/App.res
let createApolloClient = authToken => {
let headers = {
"Authorization": `Bearer ${authToken}`,
}
let httpLink = ApolloClient.Link.HttpLink.make(
~uri=_ => "https://hasura.io/learn/graphql",
~headers=Obj.magic(headers),
(),
)
+ let wsLink = {
+ open ApolloClient.Link.WebSocketLink
+ make(
+ ~uri="wss://hasura.io/learn/graphql",
+ ~options=ClientOptions.make(
+ ~connectionParams=ConnectionParams(Obj.magic({"headers": headers})),
+ ~reconnect=true,
+ (),
+ ),
+ (),
+ )
+ }
+
+ let terminatingLink = ApolloClient.Link.split(~test=({query}) => {
+ let definition = ApolloClient.Utilities.getOperationDefinition(query)
+ switch definition {
+ | Some({kind, operation}) => kind === "OperationDefinition" && operation === "subscription"
+ | None => false
+ }
+ }, ~whenTrue=wsLink, ~whenFalse=httpLink)
let client = {
open ApolloClient
make(
~cache=Cache.InMemoryCache.make(),
~connectToDevTools=true,
~defaultOptions=DefaultOptions.make(
~mutate=DefaultMutateOptions.make(~awaitRefetchQueries=true, ()),
(),
),
- ~link=httpLink,
+ ~link=terminatingLink,
(),
)
}
client
}

We configured split link to choose WebSocketLink for subscription queries and HttpLink for queries and mutations.

Close

Get Started with GraphQL Now

Hasura Cloud gives you a fully managed, production ready GraphQL API as a service to help you build modern apps faster.
Ready to get started?
Start for free on Hasura Cloud or you could contact our sales team for a detailed walk-through on how Hasura may benefit your business.
Stay in the know
Sign up for full access to our community highlights, new features, and occasional baby animal gifs! Oh, and we have a strict no-spam rule. โœŒ๏ธ