apollographql / apollographql/graphql-subscriptions
Generic types for pubSub (with solution)
- Dominant language
- TypeScript
- Stars
- 1.6k
- Forks
- 129
- PR merge metrics
- No merged PRs in 30d
Description
By adding generic to PubSubEngine, a lot of typos and (hard) type lookup can be prevented.
- [ ] has-reproduction
- [x] feature
- [ ] blocking
- [ ] good first issue
Here is an example of the type definition to look like in the end.
```
const pubSub = new PubSub<{
commentsChanged: Comment[],
postsChanged: Post[],
}>();
// `pubSub.publish` will now only accept keys listed in generic type of `pubSub` instance
// **The type must match too!**
pubSub.publish('commentAdded', { commentAdded: new Comment( /*...*/ )] });
```
Here is what needed to be done. (I looked that there is an ongoing change to rename `asyncIterator` and didn't felt like dealing with it.)
### pubsub-engine.d.ts
```
export type PubSubEngineGeneric = {
[key: string]: any;
}
export declare abstract class PubSubEngine {
abstract publish(triggerName: key, payload: { [key]: T[key] }): Promise;
abstract subscribe(triggerName: key, onMessage: Function, options: Object): Promise;
abstract unsubscribe(subId: number): any;
asyncIterator(triggers: key | key[]): AsyncIterator;
}
```
### pubsub.d.ts
```
///
import { EventEmitter } from 'events';
import { PubSubEngine, PubSubEngineGeneric } from './pubsub-engine';
export interface PubSubOptions {
eventEmitter?: EventEmitter;
}
export declare class PubSub extends PubSubEngine {
protected ee: EventEmitter;
private subscriptions;
private subIdCounter;
constructor(options?: PubSubOptions);
get(prop: key): T[key];
publish(triggerName: key, payload: { [key]: T[key] }): Promise;
subscribe(triggerName: string, onMessage: (...args: any[]) => void): Promise;
unsubscribe(subId: number): void;
}
```
Contributor guide
Research direction
Start by reading the proposed declarations in pubsub-engine.d.ts and pubsub.d.ts, then compare them with the current public types. Verify that a PubSub generic restricts trigger keys and payload values as shown, while preserving the existing subscription API. Done means the declarations support the example's type checks without breaking existing usage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- api, backend-api-design
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 42/100