From 52ee736bd2ac407952863c8e8397770bf1495a45 Mon Sep 17 00:00:00 2001 From: "netop://ウィビ" Date: Sun, 3 May 2026 12:40:04 -0700 Subject: adds support for subscriptions --- README.md | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) (limited to 'README.md') diff --git a/README.md b/README.md index 7f75f7b..1173194 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,22 @@ Companion knobs: - `enableExperimentalFragmentVariables()` - `resetCaches()` +### `GraphQLWS(options)` + +Returns a `(request: Request) => Response` handler that upgrades incoming requests to a WebSocket and speaks the [`graphql-transport-ws`](https://github.com/enisdenjo/graphql-ws) protocol. Pass it as `subscriptions` to `GraphQLHTTP` so HTTP and WS share one endpoint. + +Options: + +| Option | Type | Description | +| --------- | ------------------------------ | ------------------------------------------------------------------- | +| `context` | `(ctx) => Ctx \| Promise` | Builds the resolver context per WS connection. | +| `schema` | `GraphQLSchema` | Required. Executable schema. | +| `...` | `Partial` | Anything else `graphql-ws` accepts (`onConnect`, `onSubscribe`, …). | + +### `PubSub` + +Re-export of `graphql-subscriptions`'s in-memory pub/sub. Resolvers call `pubsub.asyncIterator(["EVENT"])` for `subscribe`; mutations call `pubsub.publish("EVENT", payload)`. For multi-process deployments swap in `graphql-redis-subscriptions` — same `PubSubEngine` interface. + ### `importQL(path)` Reads a `.graphql` file and resolves its imports. See [Loading schemas from `.graphql` files](#loading-schemas-from-graphql-files). @@ -146,6 +162,53 @@ We also export commonly imported GraphQL types: `DocumentNode`, `ExecutionResult Pinning `version` is recommended — without it the shell hits jsDelivr's `@latest` cache, which can lag behind new releases by ~12h. +## Subscriptions + +Pair `GraphQLWS` with a `PubSub` instance from `graphql-subscriptions` to serve subscriptions over WebSockets on the same endpoint as HTTP: + +```ts +import { + executeSchema, + gql, + GraphQLHTTP, + GraphQLWS, + PubSub +} from "@eol/gq"; + +const pubsub = new PubSub(); + +const schema = executeSchema({ + resolvers: { + Mutation: { + ping: (_, { msg }) => { + pubsub.publish("PING", { pinged: msg }); + return msg; + } + }, + Subscription: { + pinged: { subscribe: () => pubsub.asyncIterator(["PING"]) } + } + }, + typeDefs: gql` + type Mutation { ping(msg: String!): String } + type Subscription { pinged: String } + ` +}); + +const subscriptions = GraphQLWS({ schema }); + +Deno.serve( + { port: 4000 }, + GraphQLHTTP({ + graphiql: true, + schema, + subscriptions + }) +); +``` + +Clients connect WebSockets to the same URL using the `graphql-transport-ws` subprotocol. The bundled GraphiQL detects subscription operations and switches transports automatically. See `subscription-example.ts` for a runnable demo. + ## License MIT -- cgit v1.2.3