Skip to content

Commit

Permalink
made mercurius's implicitly injected pubsub subscribe/publish methods…
Browse files Browse the repository at this point in the history
… type safe (#1115)

* make topics/payloads of default pubsub module type safe and extendable

* fix incorrect use of generics in `pubsub.subscribe` method
  • Loading branch information
adrtivv authored Jan 14, 2025
1 parent f0aaf00 commit da5c53b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
18 changes: 15 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,21 @@ import { Readable } from 'stream'
type Mercurius = typeof mercurius

declare namespace mercurius {
export interface PubSub {
subscribe<TResult = any>(topics: string | string[]): Promise<Readable & AsyncIterableIterator<TResult>>;
publish<TResult = any>(event: { topic: string; payload: TResult }, callback?: () => void): void;
export interface PubSubTopics {
[topic: string]: any;
}

export interface PubSub<TPubSubTopics extends PubSubTopics = PubSubTopics> {
subscribe<TTopic extends Extract<keyof TPubSubTopics, string>>(
topics: TTopic | TTopic[],
): Promise<Readable & AsyncIterableIterator<TPubSubTopics[TTopic]>>;
publish<TTopic extends Extract<keyof TPubSubTopics, string>>(
event: {
topic: TTopic;
payload: TPubSubTopics[TTopic];
},
callback?: () => void,
): void;
}

export interface MercuriusContext {
Expand Down
2 changes: 1 addition & 1 deletion test/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ app.graphql.pubsub.publish({
})

async () => {
const subscription = await app.graphql.pubsub.subscribe<{ newNotification: string }>('topic')
const subscription = await app.graphql.pubsub.subscribe('topic')

subscription.on('data', (chunk) => {
console.log(chunk)
Expand Down

0 comments on commit da5c53b

Please sign in to comment.