apollographql / graphql-subscriptions

:newspaper: A small module that implements GraphQL subscriptions for Node.js
MIT License
1.58k stars 133 forks source link

Add a(n optional) generic type map to PubSub. #245

Closed mchccn closed 2 years ago

mchccn commented 3 years ago

The class PubSub now has a generic type parameter so its methods publish and subscribe can be optionally type-checked by TypeScript.

/label typedefs

I was using apollo-server-express but the class PubSub did not have any compile time validation by TypeScript. So I extended the class and added a generic. I thought I would contribute to the project back since it will be useful to others.

New usage:

import { PubSub } from "apollo-server-express";

const pubsub = new PubSub<{
    EVENT_ONE: { data: number; };
    EVENT_TWO: { data: string; };
}>();

pubsub.publish("EVENT_ONE", { data: 42 });
pubsub.publish("EVENTONE", { data: 42 }); // ! ERROR
pubsub.publish("EVENT_ONE", { data: "42" }); // ! ERROR
pubsub.publish("EVENT_TWO", { data: "hello" });

pubsub.subscribe("EVENT_ONE", () => {});
pubsub.subscribe("EVENTONE", () => {}); // ! ERROR
pubsub.subscribe("EVENT_TWO", () => {});

const oldPubSub = new PubSub(); // => Still completely fine and should act as if the optional generic was never added.
mchccn commented 2 years ago

Yep! I updated the README as well to feature this if it ever gets merged.

mchccn commented 2 years ago

Related: #223

n1ru4l commented 2 years ago

@glasser This is something that should be added to the v3.0 release: https://github.com/apollographql/graphql-subscriptions/milestone/1

This has been out here for a while: https://github.com/contra/typed-graphql-subscriptions