Examples: Subscriptions
Real-time data updates using GraphQL subscriptions over WebSockets.
Table of Contents
Setup
Apollo Client with Subscriptions
import { ApolloClient, InMemoryCache, split, HttpLink } from '@apollo/client'
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import { getMainDefinition } from '@apollo/client/utilities'
import { createClient } from 'graphql-ws'
const httpLink = new HttpLink({
uri: 'https://sai-keeper.testnet-2.nibiru.fi/graphql'
})
const wsLink = new GraphQLWsLink(
createClient({
url: 'wss://sai-keeper.testnet-2.nibiru.fi/graphql',
connectionParams: {
// Add auth headers if needed
},
retryAttempts: 5,
shouldRetry: () => true
})
)
// Split link based on operation type
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
wsLink,
httpLink
)
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache()
})urql with Subscriptions
Perp Subscriptions
Example 1: Watch User Trades
Subscribe to all trade updates for a specific user.
Example 2: Watch Trade Events
Subscribe to trade history events (opens, closes, liquidations, etc).
Example 3: Watch Market Borrowing Rates
Subscribe to real-time borrowing rate updates for a specific market.
Example 4: Watch All Markets
Subscribe to updates for all available markets.
LP Subscriptions
Example 5: Watch Vault Metrics
Subscribe to real-time vault updates (TVL, APY, share price).
Example 6: Watch User LP Positions
Subscribe to user's LP deposit updates.
Example 7: Watch Deposit Events
Subscribe to deposit/withdrawal events.
Example 8: Watch Withdrawal Requests
Subscribe to withdrawal request updates.
Oracle Subscriptions
Example 9: Watch Token Prices
Subscribe to real-time price updates.
Example 10: Watch Specific Token Price
Example 11: Watch User Balances
Advanced Patterns
Example 12: Multiple Subscriptions Manager
Example 13: Subscription with Reconnection Logic
Best Practices
1. Always Clean Up Subscriptions
2. Handle Connection States
3. Debounce Rapid Updates
4. Combine with Queries for Initial Data
Last updated