From 2bbc43505e48b89acd802d6c09d8bb03d5561bfc Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:22:01 -0500 Subject: [PATCH 1/7] feat: parse application/x-www-form-urlencoded request bodies Signed-off-by: Diego Resendez --- src/http.ts | 2 ++ test/http.test.ts | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/http.ts b/src/http.ts index c4602c0..f08a63e 100644 --- a/src/http.ts +++ b/src/http.ts @@ -207,6 +207,8 @@ export function createHttpServer( res.end(JSON.stringify({ error: 'Invalid JSON body' })); return; } + } else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) { + body = Object.fromEntries(new URLSearchParams(raw)); } let result: PipelineResult; try { diff --git a/test/http.test.ts b/test/http.test.ts index f94b407..468592e 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -137,4 +137,18 @@ describe('request hardening', () => { expect(text).toContain('data: {"n":3}'); server.close(); }); + + it('parses application/x-www-form-urlencoded into an object body', async () => { + const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`; + const server = createHttpServer([{ + method: 'POST', pattern: '/form', transport: 'buffer', + handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(req.body) }), + }]); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getUrl(server)}/form`, { + method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'a=1&b=two', + }); + expect(await res.json()).toEqual({ a: '1', b: 'two' }); + server.close(); + }); }); From 6171e5e6bdb8a49f41005cb393ed79ccfa5b733e Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:23:54 -0500 Subject: [PATCH 2/7] feat: rooms broadcast-hub primitive, auto-provided to handlers Signed-off-by: Diego Resendez --- src/app.ts | 9 +++++++++ src/index.ts | 1 + src/rooms.ts | 11 +++++++++++ test/app.test.ts | 19 +++++++++++++++++++ test/rooms.test.ts | 28 ++++++++++++++++++++++++++++ 5 files changed, 68 insertions(+) create mode 100644 src/rooms.ts create mode 100644 test/rooms.test.ts diff --git a/src/app.ts b/src/app.ts index 7d1af04..00a58ef 100644 --- a/src/app.ts +++ b/src/app.ts @@ -13,6 +13,7 @@ import { } from './metadata'; import { getArgs, getHandlerNeeds, resolveArgs } from './params'; import { connectLink, type Link } from './mesh/link'; +import { Rooms } from './rooms'; import { buildRemote } from './mesh/teacup'; import { buildManifest, createMeshControl } from './mesh/teapot'; import type { MeshControl } from './http'; @@ -126,6 +127,14 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me setRunner(n.name, n.run); } + // built-in: auto-provide a shared Rooms instance (unless the user declares one) + if (!runners.has('rooms')) { + const roomsInstance = new Rooms(); + providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' }); + providerMeta.set('rooms', { optional: false }); + setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms + } + // For each route, resolve which providers/steps feed it via topo order. // MVP: every route depends on every declared step + provider in the app graph. // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. diff --git a/src/index.ts b/src/index.ts index 5f098fc..cbaa2e0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,6 +16,7 @@ export { needs, ctx, param, query, body, headers } from './params'; export type { Query, Headers, Context, ArgSpec } from './params'; export { channel, isAsyncIterable } from './channel'; export type { Channel } from './channel'; +export { Rooms } from './rooms'; export { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; export type { Transport, HttpMethod } from './metadata'; export { inbound, abort } from './params'; diff --git a/src/rooms.ts b/src/rooms.ts new file mode 100644 index 0000000..7eee41b --- /dev/null +++ b/src/rooms.ts @@ -0,0 +1,11 @@ +import { channel, type Channel } from './channel'; + +export class Rooms { + private readonly hubs = new Map>(); + room(name: string): Channel { + let hub = this.hubs.get(name); + if (!hub) { hub = channel(); this.hubs.set(name, hub); } + return hub as unknown as Channel; + } + names(): string[] { return [...this.hubs.keys()]; } +} diff --git a/test/app.test.ts b/test/app.test.ts index d555167..6ed9190 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -216,6 +216,7 @@ describe('per-route subgraph slicing', () => { }); }); +import { Rooms } from '../src/rooms'; import { toMermaid as renderMermaid } from '../src/graph-viz'; describe('app.graph / explain', () => { @@ -317,3 +318,21 @@ describe('overrides', () => { await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/); }); }); + +describe('rooms auto-provide', () => { + it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => { + @Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } } + @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M] }); + const s = await app.listen(0); + const port = (s.address() as any).port; + expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true }); + s.close(); + }); + it('a user-declared rooms provider wins (no duplicate-name throw)', () => { + @Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } } + @Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } } + @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {} + expect(() => createApp({ modules: [M] })).not.toThrow(); + }); +}); diff --git a/test/rooms.test.ts b/test/rooms.test.ts new file mode 100644 index 0000000..1f56de5 --- /dev/null +++ b/test/rooms.test.ts @@ -0,0 +1,28 @@ +import { describe, it, expect } from 'vitest'; +import { Rooms } from '../src/rooms'; + +describe('Rooms', () => { + it('returns the same shared channel for a given name', () => { + const r = new Rooms(); + expect(r.room('general')).toBe(r.room('general')); + expect(r.room('a')).not.toBe(r.room('b')); + }); + it('broadcasts a push to all current subscribers of a room', async () => { + const r = new Rooms(); + const hub = r.room('x'); + const a = hub[Symbol.asyncIterator](); + const b = hub[Symbol.asyncIterator](); + await Promise.resolve(); + hub.push(7); + expect((await a.next()).value).toBe(7); + expect((await b.next()).value).toBe(7); + }); + it('isolates distinct rooms', async () => { + const r = new Rooms(); + const it = r.room('a')[Symbol.asyncIterator](); + await Promise.resolve(); + r.room('b').push(1); + r.room('a').push(2); + expect((await it.next()).value).toBe(2); + }); +}); From 9050a7e5d920ff888279d8a6dcffee0f92947303 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:25:24 -0500 Subject: [PATCH 3/7] feat: WS connections rejected by an HttpError close with 4000+status Signed-off-by: Diego Resendez --- src/http.ts | 9 +++++++-- test/ws.test.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/http.ts b/src/http.ts index f08a63e..840a9be 100644 --- a/src/http.ts +++ b/src/http.ts @@ -2,7 +2,7 @@ import http from 'http'; import { once } from 'events'; import { channel } from './channel'; import { errorToResponse } from './transformers'; -import { HttpError } from './signals'; +import { HttpError, isHttpError } from './signals'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; import type { Transport } from './metadata'; @@ -167,7 +167,12 @@ function attachWs( try { ws.close(); } catch { /* already closed */ } } catch (err) { bus?.emit('stream:error', { name, error: err }); - try { ws.close(1011); } catch { /* already closed */ } + if (isHttpError(err)) { + const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); + try { ws.close(4000 + err.status, reason); } catch { /* already closed */ } + } else { + try { ws.close(1011); } catch { /* already closed */ } + } } finally { ac.abort(); bus?.emit('stream:close', { name }); diff --git a/test/ws.test.ts b/test/ws.test.ts index 571e9c3..ec58541 100644 --- a/test/ws.test.ts +++ b/test/ws.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'; import WebSocket from 'ws'; import { channel } from '../src/channel'; import { createHttpServer, type WsRouteDef } from '../src/http'; +import { Unauthorized } from '../src/signals'; const url = (server: import('http').Server, path: string) => { const a = server.address(); @@ -34,4 +35,19 @@ describe('ws upgrade', () => { expect(aborted).toBe(true); server.close(); }); + + it('closes with a 4000+status code when the WS open() throws an HttpError', async () => { + const wsRoutes = [{ pattern: '/secure', open: async () => { throw new Unauthorized('no token'); } }]; + const server = createHttpServer([], wsRoutes as any); + await new Promise((r) => server.listen(0, r)); + const port = (server.address() as any).port; + const WebSocket = (await import('ws')).default; + const client = new WebSocket(`ws://127.0.0.1:${port}/secure`); + const { code, reason } = await new Promise<{ code: number; reason: string }>((res) => { + client.on('close', (code: number, reason: Buffer) => res({ code, reason: reason.toString() })); + }); + expect(code).toBe(4401); + expect(reason).toContain('no token'); + server.close(); + }); }); From 3842271c4d0b316046a1e5d43932f12bbdd67c80 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:28:42 -0500 Subject: [PATCH 4/7] feat(example): in-memory CRUD with query and JSON/urlencoded bodies Signed-off-by: Diego Resendez --- example/crud.ts | 91 ++++++++++++++++++++++++++++++++++++++ test/examples/crud.test.ts | 28 ++++++++++++ 2 files changed, 119 insertions(+) create mode 100644 example/crud.ts create mode 100644 test/examples/crud.test.ts diff --git a/example/crud.ts b/example/crud.ts new file mode 100644 index 0000000..97aae4e --- /dev/null +++ b/example/crud.ts @@ -0,0 +1,91 @@ +import { + createApp, Provider, Route, + Get, Post, Put, Patch, Delete, + Module, needs, param, query, body, NotFound, +} from '../src/index'; + +interface Todo { id: string; title: string; done: boolean } + +interface Store { + todos: Map; + next(): string; +} + +@Provider({ provides: 'store' }) +class TodoStore { + private counter = 0; + private readonly todos: Map = new Map(); + + provide(): { store: Store } { + const store: Store = { + todos: this.todos, + next: () => String(++this.counter), + }; + return { store }; + } +} + +@Route('/todos') +class TodoController { + @Get('/') + list(@needs('store') store: Store, @query('done') done: string | undefined): Todo[] { + const all = [...store.todos.values()]; + if (done !== undefined) { + const flag = done === 'true'; + return all.filter((t) => t.done === flag); + } + return all; + } + + @Get('/:id') + get(@needs('store') store: Store, @param('id') id: string): Todo { + const todo = store.todos.get(id); + if (!todo) throw new NotFound(`todo ${id} not found`); + return todo; + } + + @Post('/') + create(@needs('store') store: Store, @body() data: Record): Todo { + const id = store.next(); + const todo: Todo = { id, title: String(data.title ?? ''), done: false }; + store.todos.set(id, todo); + return todo; + } + + @Put('/:id') + replace(@needs('store') store: Store, @param('id') id: string, @body() data: Record): Todo { + if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`); + const todo: Todo = { id, title: String(data.title ?? ''), done: Boolean(data.done ?? false) }; + store.todos.set(id, todo); + return todo; + } + + @Patch('/:id') + merge(@needs('store') store: Store, @param('id') id: string, @body() data: Record): Todo { + const todo = store.todos.get(id); + if (!todo) throw new NotFound(`todo ${id} not found`); + const updated: Todo = { + id, + title: 'title' in data ? String(data.title) : todo.title, + done: 'done' in data ? Boolean(data.done) : todo.done, + }; + store.todos.set(id, updated); + return updated; + } + + @Delete('/:id') + remove(@needs('store') store: Store, @param('id') id: string): { deleted: string } { + if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`); + store.todos.delete(id); + return { deleted: id }; + } +} + +@Module({ mountpoint: '/api', providers: [TodoStore], controllers: [TodoController] }) +class TodoModule {} + +export const app = createApp({ modules: [TodoModule] }); + +if (require.main === module) { + app.listen(3300).then(() => console.log('green-tea crud on http://localhost:3300')); +} diff --git a/test/examples/crud.test.ts b/test/examples/crud.test.ts new file mode 100644 index 0000000..f97e236 --- /dev/null +++ b/test/examples/crud.test.ts @@ -0,0 +1,28 @@ +import { describe, it, expect, afterAll } from 'vitest'; +import { app } from '../../example/crud'; + +let base: string; let server: any; +const url = (p: string) => `${base}${p}`; +afterAll(() => server?.close()); + +describe('crud example', () => { + it('supports create / read / update / delete', async () => { + server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`; + const created = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'a' }) }).then((r) => r.json() as Promise<{ id: string; title: string; done: boolean }>); + expect(created).toMatchObject({ title: 'a' }); + const id = created.id; + expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ title: 'a' }); + await fetch(url(`/api/todos/${id}`), { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ done: true }) }); + expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ done: true }); + const list = await fetch(url('/api/todos')).then((r) => r.json()); + expect(Array.isArray(list)).toBe(true); + const del = await fetch(url(`/api/todos/${id}`), { method: 'DELETE' }); + expect(del.status).toBe(200); + expect((await fetch(url(`/api/todos/${id}`))).status).toBe(404); + }); + + it('accepts urlencoded form bodies', async () => { + const res = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'title=form' }); + expect(await res.json()).toMatchObject({ title: 'form' }); + }); +}); From 8335ff28754bc7bee9ac84cdf47b276b887c7018 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:30:16 -0500 Subject: [PATCH 5/7] feat(example): WS chat with rooms and handshake auth (no socket.io) Signed-off-by: Diego Resendez --- example/chat.ts | 29 +++++++++++++++++++++++++++++ test/examples/chat.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 example/chat.ts create mode 100644 test/examples/chat.test.ts diff --git a/example/chat.ts b/example/chat.ts new file mode 100644 index 0000000..0c040e5 --- /dev/null +++ b/example/chat.ts @@ -0,0 +1,29 @@ +import { createApp, Step, Route, Ws, Module, Unauthorized, param, needs, inbound, Rooms } from '../src/index'; + +@Step({ provides: 'user', needs: [] }) +class Authenticate { + run(ctx: any) { + const token = ctx.query?.token; // steps read ctx directly (no @query on steps) + if (!token) throw new Unauthorized('token required'); + return { user: { id: String(token) } }; + } +} + +@Route('/chat') +class ChatController { + @Ws('/:room') + join(@param('room') room: string, @needs('user') user: any, @needs('rooms') rooms: Rooms, @inbound() incoming: AsyncIterable) { + const hub = rooms.room(room); + (async () => { for await (const msg of incoming) hub.push(`${user.id}: ${msg}`); })().catch(() => {}); // fire-and-forget pump + return hub; // broadcast as the outbound channel + } +} + +@Module({ mountpoint: '/', steps: [Authenticate], controllers: [ChatController] }) +class ChatModule {} + +export const app = createApp({ modules: [ChatModule] }); + +if (require.main === module) { + app.listen(4100).then(() => console.log('chat on ws://localhost:4100/chat/:room?token=...')); +} diff --git a/test/examples/chat.test.ts b/test/examples/chat.test.ts new file mode 100644 index 0000000..4ea912c --- /dev/null +++ b/test/examples/chat.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect, afterAll } from 'vitest'; +import { app } from '../../example/chat'; + +let server: any; let port: number; +afterAll(() => server?.close()); + +describe('chat example', () => { + it('two authed clients in a room see each other; missing token is rejected 4401', async () => { + server = await app.listen(0); port = (server.address() as any).port; + const WebSocket = (await import('ws')).default; + + const a = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=alice`); + const b = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=bob`); + await Promise.all([new Promise((r) => a.on('open', r)), new Promise((r) => b.on('open', r))]); + const bGot = new Promise((r) => b.on('message', (d: Buffer) => r(d.toString()))); + await new Promise((r) => setTimeout(r, 50)); // let server-side open()/subscribe complete (channel has no replay) + a.send('hi'); + expect(await bGot).toContain('hi'); + a.close(); b.close(); + + const noTok = new WebSocket(`ws://127.0.0.1:${port}/chat/general`); + const code = await new Promise((r) => noTok.on('close', (c: number) => r(c))); + expect(code).toBe(4401); + }); +}); From 0c29c76a8aa819bea948968c1f65ff30fa18d2ee Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:37:33 -0500 Subject: [PATCH 6/7] fix(http): flush SSE headers immediately so idle subscriptions don't deadlock clients Signed-off-by: Diego Resendez --- src/http.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/http.ts b/src/http.ts index 840a9be..adf4252 100644 --- a/src/http.ts +++ b/src/http.ts @@ -91,6 +91,7 @@ async function pipeStream( bus?: Bus, name = '', streams?: Set<() => void>, ): Promise { res.writeHead(200, encoder.headers); + res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers bus?.emit('stream:open', { name }); const it = stream[Symbol.asyncIterator](); let ping: ReturnType | undefined; From c39eb667ace80ef895dc64d9cc0a8bc848fdf734 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 13:37:37 -0500 Subject: [PATCH 7/7] feat(example): minimal GraphQL with query/mutation and an SSE subscription over rooms Signed-off-by: Diego Resendez --- docs/quickstart.md | 34 +++++++++++++++++++++++++ example/graphql.ts | 47 +++++++++++++++++++++++++++++++++++ package-lock.json | 19 ++++++++++++++ package.json | 1 + test/examples/graphql.test.ts | 24 ++++++++++++++++++ 5 files changed, 125 insertions(+) create mode 100644 example/graphql.ts create mode 100644 test/examples/graphql.test.ts diff --git a/docs/quickstart.md b/docs/quickstart.md index d7fcdbe..552729c 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -269,6 +269,40 @@ const app = createApp({ Overrides replace only the named token's runner; the rest of the graph is untouched. +## Runnable examples + +The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom. + +### CRUD — methods, query, JSON & urlencoded body + +`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`, +read the payload via `@body()` — the same handler accepts both `application/json` and +`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing +rows throw `NotFound` (→ 404). + +See [`example/crud.ts`](../example/crud.ts). + +### Chat — rooms + handshake auth + +A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token — +which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the +`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, +so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms` +primitive (one instance app-wide). + +See [`example/chat.ts`](../example/chat.ts). + +### GraphQL — query/mutation over POST, subscription over SSE + +A schema built programmatically with `graphql` (a dev/example dependency — the core has no +runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The +`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route +calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`, +and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is +the tie between GraphQL, green-tea streams, and the `rooms` primitive. + +See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first. + ## The one rule to remember ``` diff --git a/example/graphql.ts b/example/graphql.ts new file mode 100644 index 0000000..720c349 --- /dev/null +++ b/example/graphql.ts @@ -0,0 +1,47 @@ +import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLNonNull, graphql, subscribe, parse } from 'graphql'; +import { createApp, Route, Post, Sse, Module, body, needs, isAsyncIterable, Rooms } from '../src/index'; + +interface Message { text: string } +const store: Message[] = []; +const MessageType = new GraphQLObjectType({ name: 'Message', fields: { text: { type: GraphQLString } } }); + +function buildSchema(rooms: Rooms): GraphQLSchema { + return new GraphQLSchema({ + query: new GraphQLObjectType({ name: 'Query', fields: { + messages: { type: new GraphQLList(MessageType), resolve: () => store }, + } }), + mutation: new GraphQLObjectType({ name: 'Mutation', fields: { + postMessage: { type: MessageType, args: { text: { type: new GraphQLNonNull(GraphQLString) } }, + resolve: (_root, { text }: { text: string }) => { const m = { text }; store.push(m); rooms.room('messages').push(m); return m; } }, + } }), + subscription: new GraphQLObjectType({ name: 'Subscription', fields: { + messageAdded: { type: MessageType, + subscribe: () => rooms.room('messages'), // Channel is the AsyncIterable source + resolve: (payload: Message) => payload }, + } }), + }); +} + +@Route('/graphql') +class GraphQLController { + @Post('') + async run(@body() input: any, @needs('rooms') rooms: Rooms) { + return graphql({ schema: buildSchema(rooms), source: input?.query ?? '', variableValues: input?.variables }); + } + + @Sse('/stream') + async stream(@needs('rooms') rooms: Rooms) { + const result = await subscribe({ schema: buildSchema(rooms), document: parse('subscription { messageAdded { text } }') }); + if (!isAsyncIterable(result)) throw new Error('subscription failed'); // subscribe() returns a single ExecutionResult on error + return result; + } +} + +@Module({ mountpoint: '/', controllers: [GraphQLController] }) +class GraphQLModule {} + +export const app = createApp({ modules: [GraphQLModule] }); + +if (require.main === module) { + app.listen(4200).then(() => console.log('graphql on http://localhost:4200/graphql')); +} diff --git a/package-lock.json b/package-lock.json index ad8d4ec..1e3ee1c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,9 +14,18 @@ "devDependencies": { "@types/node": "^18.19.0", "@types/ws": "^8.18.1", + "graphql": "^16.9.0", "typescript": "^5.5.0", "vitest": "^2.0.0", "ws": "^8.21.0" + }, + "peerDependencies": { + "ws": "^8.18.0" + }, + "peerDependenciesMeta": { + "ws": { + "optional": true + } } }, "node_modules/@esbuild/aix-ppc64": { @@ -1063,6 +1072,16 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/graphql": { + "version": "16.14.2", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz", + "integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" + } + }, "node_modules/loupe": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", diff --git a/package.json b/package.json index de2f292..2e69fa2 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "devDependencies": { "@types/node": "^18.19.0", "@types/ws": "^8.18.1", + "graphql": "^16.9.0", "typescript": "^5.5.0", "vitest": "^2.0.0", "ws": "^8.21.0" diff --git a/test/examples/graphql.test.ts b/test/examples/graphql.test.ts new file mode 100644 index 0000000..8d07363 --- /dev/null +++ b/test/examples/graphql.test.ts @@ -0,0 +1,24 @@ +import { describe, it, expect, afterAll } from 'vitest'; +import { app } from '../../example/graphql'; + +let server: any; let base: string; +afterAll(() => server?.close()); +const gql = (query: string, variables?: any) => + fetch(`${base}/graphql`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query, variables }) }).then((r) => r.json() as Promise); + +describe('graphql example', () => { + it('runs a query and a mutation, and streams a subscription over SSE', async () => { + server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`; + + expect(await gql('{ messages { text } }')).toMatchObject({ data: { messages: expect.any(Array) } }); + + const res = await fetch(`${base}/graphql/stream`, { headers: { accept: 'text/event-stream' } }); + const reader = res.body!.getReader(); + await new Promise((r) => setTimeout(r, 50)); // let the subscription subscribe to the room before publishing + await gql('mutation($t:String!){ postMessage(text:$t){ text } }', { t: 'hello-sub' }); + const dec = new TextDecoder(); let buf = ''; + while (!buf.includes('hello-sub')) buf += dec.decode((await reader.read()).value); + expect(buf).toContain('hello-sub'); + await reader.cancel(); + }); +});