Examples: Subscriptions
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
Example 2: Watch Trade Events
Example 3: Watch Market Borrowing Rates
Example 4: Watch All Markets
LP Subscriptions
Example 5: Watch Vault Metrics
Example 6: Watch User LP Positions
Example 7: Watch Deposit Events
Example 8: Watch Withdrawal Requests
Oracle Subscriptions
Example 9: Watch Token Prices
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