Skip to content

docs: add guide on subscriptions #4406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 28, 2025

Conversation

sarahxsanders
Copy link
Contributor

Guide for subscriptions

@sarahxsanders
Copy link
Contributor Author

sarahxsanders commented May 22, 2025

@JoviDeCroock the prettier ci check is failing for _meta.ts but it looks correct

**DISREGARD :)

@JoviDeCroock JoviDeCroock merged commit 4e9df42 into graphql:16.x.x May 28, 2025
20 checks passed
Copy link
Member

@benjie benjie left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Absolutely excellent 🙌

Create a `PubSub` instance to manage your in-memory event system:

```js
import { PubSub } from 'graphql-subscriptions';
Copy link
Member

@ardatan ardatan May 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Besides this unmaintained library, we have an alternative package @graphql-yoga/subscriptions that uses the standard EventTarget, and it also allows you to use other event sources like Redis.

import { createPubSub } from '@graphql-yoga/subscriptions'
import { Redis } from 'ioredis'
import { createRedisEventTarget } from '@graphql-yoga/redis-event-target'
 
const publishClient = new Redis()
const subscribeClient = new Redis()
 
const eventTarget = createRedisEventTarget({
  publishClient,
  subscribeClient
})
 
const pubSub = createPubSub({ eventTarget })

And it is fully type safe compared to graphql-subscriptions;

const pubSub = createPubSub<{
  randomNumber: [randomNumber: number]
}>()
 
// Usage outside a GraphQL subscribe function
async function subscribe() {
  const eventSource = pubSub.subscribe('randomNumber')
 
  for await (const value of eventSource) {
    console.log(value)
    // dispose subscription after the first event has been published.
    eventSource.return()
  }
}
 
subscribe()
 
pubSub.publish('randomNumber', 3)

yaacovCR pushed a commit to yaacovCR/graphql-js that referenced this pull request May 30, 2025
yaacovCR pushed a commit that referenced this pull request May 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants