## Demo: chat ### Chat.svelte ```svelte ``` ### ChatWidget.svelte ```svelte
Chat
{#each messages as msg, i (i)}
{msg.text}
{/each} {#if messages.length === 0}
Send a message to get started
{/if}
``` ### routes.ts ```ts import { Mochi } from 'mochi-framework'; import type { MochiRouteValue } from 'mochi-framework'; export const routes: Record = { '/demos/chat': Mochi.page('./src/demos/chat/Chat.svelte'), '/ws/chat': (() => { const history: string[] = []; const TOPIC = 'chat'; return Mochi.ws({ open(ws) { ws.subscribe(TOPIC); for (const msg of history) { ws.send(msg); } }, message(ws, message) { const text = String(message); history.push(text); // send to all subscribers including the sender ws.publish(TOPIC, text); ws.send(text); }, close(ws) { ws.unsubscribe(TOPIC); }, }); })(), }; ``` ### index.ts ```ts import { Mochi, logger } from 'mochi-framework'; await Mochi.serve({ port: 3333, development: process.env.MODE === 'development', routes: { '/': Mochi.page('./src/Home.svelte'), }, }); logger.info('Server running at http://localhost:3333'); ```