feat(example): WS chat with rooms and handshake auth (no socket.io)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+54
No files matched your search
@@ -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,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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user