GQLoom

Subscription

In GraphQL, Subscription allows the server to push data to the client.

Basic Usage

In GQLoom, we use the subscription function to define a subscription:.

import { , ,  } from "@gqloom/core"
import {  } from "@gqloom/valibot"
import * as  from "valibot"
import {  } from "node:http"
import {  } from "graphql-yoga"
 
const  = ({
  : (.())
    .({ : .(.(), .()) })
    .(async function* () {
      for (let  = .;  >= 0; --) {
        await new (() => (, 1000))
        yield 
      }
    }),
})
 
const  = ()
const  = ({  })
const  = ()
 
.(4000, () => {
  .("Server is running on http://localhost:4000/graphql")
})

In the code above, we define a countdown subscription that accepts a seconds parameter. We passed in an asynchronous generator in the subscription function, which will push a number every second until the number is 0.

Using publish/subscribe

We can also use the publish/subscribe feature provided by GraphQL Yoga to push messages more easily:

import { , ,  } from "@gqloom/core"
import {  } from "graphql-yoga"
import * as  from "valibot"
 
const  = <{ : [string] }>()
 
const  = ({
  : (.())
    .({ : .() })
    .(({  }) => {
      const  = `Hello, ${}`
      .("greeting", )
      return 
    }),
 
  : (.())
    .(() => .("greeting"))
    .(() => ),
})

In the code above, we defined a hello query and a listenGreeting subscription. When the hello query is called, it publishes a greeting event, and the listenGreeting subscription subscribes to this event and pushes a message when it occurs.

You can learn about the detailed usage of the Publish/Subscribe feature at GraphQL Yoga Documentation.

Using Subscriptions in Distributed Systems

The subscription feature can work easily in a monolithic application. However, in a distributed system, the subscription feature can get complicated. You may consider using the event-driven federated subscription feature from WunderGraph Cosmo to handle subscriptions in a distributed system.

On this page