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); + }); +});