Sign up for Hasura Newsletter
Loading...

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.

Did you find this page helpful?
Start with GraphQL on Hasura for Free
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2022 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin