Skip to content

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