typed-graphql-subscriptions
v0.0.1
Published
Type-safe PubSub wrapper for GraphQL subscriptions
Downloads
1,090
Maintainers
Readme
typed-graphql-subscriptions
Type-safe PubSub wrapper for GraphQL subscriptions
Installation
npm install typed-graphql-subscriptions
Usage
Create a TypeScript type mapping the name of each PubSub channel to a Tuple that represents the arguments that will be passed to publish
.
type Channels = {
announcementCreated: [{ body: string }];
};
More commonly, you want to utilize a composite name for your channel where chatMessageReceived:42
and chatMessageReceived:43
are separate channels but share the same type for the payload. We can define the types for these channels like this:
type Channels = {
announcementCreated: [{ body: string }];
chatMessageReceived: [number, { body: string }];
};
Create a PubSub instance and pass it to TypedPubSub
's contructor, making sure to include the generic type variable:
import { PubSub } from "graphql-subscriptions";
import { TypedPubSub } from "typed-graphql-subscriptions";
const pubSub = new PubSub();
const typedPubSub = new TypedPubSub<Channels>(pubSub);
Note: You can use any PubSub implementation you like (for example, this one), as long as it implements
PubSubEngine
.
Now you can safely invoke subscribe
using either two or three arguments:
typedPubSub.publish("announcementCreated", {
body: "Site is down for maintenance.",
});
typedPubSub.publish("chatMessageReceived", 42, { message: "Hello." });
The asyncIterator
method is called similarly:
typedPubSub.asyncIterator("announcementCreated");
typedPubSub.asyncIterator("chatMessageReceived", 42);