DEV Community

joehua87
joehua87

Posted on

3

Simple way to use Abinsthe Subscription in urql

Benefits

  • Without install @absinthe/socket which contains some legacy package; also save 16kb gzip
import { subscriptionExchange } from '@urql/core'
import { Channel, Socket } from 'phoenix'
import { make, pipe, toObservable } from 'wonka'

import { getWsEndpoint } from '~/env'

const wsEndpoint = getWsEndpoint()
const socket = new Socket(`${wsEndpoint}/socket`, {})

socket.connect()
const absintheChannel = socket.channel('__absinthe__:control')
absintheChannel.join()

export const absintheExchange = subscriptionExchange({
  forwardSubscription({ query, variables }) {
    let subscriptionChannel: Channel

    const source = make((observer) => {
      const { next } = observer

      absintheChannel.push('doc', { query, variables }).receive('ok', (v) => {
        const subscriptionId = v.subscriptionId

        if (subscriptionId) {
          subscriptionChannel = socket.channel(subscriptionId)
          subscriptionChannel.on('subscription:data', (value) => {
            next(value.result)
          })
        }
      })

      return () => {
        subscriptionChannel?.leave()
      }
    })

    return pipe(source, toObservable)
  },
})
Enter fullscreen mode Exit fullscreen mode

Then

const endpoint = getEndpoint()

export const client = createClient({
  url: `${endpoint}/graphql`,
  exchanges: [
    dedupExchange,
    fetchExchange,
    absintheExchange,
  ],
})

Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay