Merge feature/dx-adoption: usable for small apps + showcase examples
CI / build (push) Has been cancelled
CI / build (push) Has been cancelled
Core: urlencoded body parsing, a rooms broadcast-hub primitive (auto-provided), WS auth rejection close-code (4000+status), and an SSE header-flush fix for idle subscriptions. Examples: CRUD, WS chat with rooms + handshake auth (no socket.io), and minimal GraphQL with an SSE subscription over rooms (graphql is a devDep; core stays zero-dep). Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
17 files changed
+406
-2
No files matched your search
@@ -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
|
||||
|
||||
```
|
||||
|
||||
@@ -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<string>) {
|
||||
const hub = rooms.room<string>(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=...'));
|
||||
}
|
||||
@@ -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<string, Todo>;
|
||||
next(): string;
|
||||
}
|
||||
|
||||
@Provider({ provides: 'store' })
|
||||
class TodoStore {
|
||||
private counter = 0;
|
||||
private readonly todos: Map<string, Todo> = 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<string, unknown>): 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<string, unknown>): 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<string, unknown>): 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'));
|
||||
}
|
||||
@@ -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<Message>('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'));
|
||||
}
|
||||
Generated
+19
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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.
|
||||
|
||||
+10
-2
@@ -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';
|
||||
@@ -91,6 +91,7 @@ async function pipeStream(
|
||||
bus?: Bus, name = '', streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
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<typeof setInterval> | undefined;
|
||||
@@ -167,7 +168,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 });
|
||||
@@ -207,6 +213,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 {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { channel, type Channel } from './channel';
|
||||
|
||||
export class Rooms {
|
||||
private readonly hubs = new Map<string, Channel<unknown>>();
|
||||
room<T = unknown>(name: string): Channel<T> {
|
||||
let hub = this.hubs.get(name);
|
||||
if (!hub) { hub = channel<unknown>(); this.hubs.set(name, hub); }
|
||||
return hub as unknown as Channel<T>;
|
||||
}
|
||||
names(): string[] { return [...this.hubs.keys()]; }
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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<string>((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<number>((r) => noTok.on('close', (c: number) => r(c)));
|
||||
expect(code).toBe(4401);
|
||||
});
|
||||
});
|
||||
@@ -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' });
|
||||
});
|
||||
});
|
||||
@@ -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<any>);
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<void>((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();
|
||||
});
|
||||
});
|
||||
@@ -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<number>('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<number>('a')[Symbol.asyncIterator]();
|
||||
await Promise.resolve();
|
||||
r.room<number>('b').push(1);
|
||||
r.room<number>('a').push(2);
|
||||
expect((await it.next()).value).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -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<void>((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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user