Chat room
This example creates a small chat API with join, publish, presence, members, and history routes.
Configure the app
Section titled “Configure the app”import { backend } from "@layeron/core"import { realtime } from "@layeron/modules"
const app = backend()const live = realtime({ name: "chat", historyLimit: 100,})app.use(live)Join the chat room
Section titled “Join the chat room”app.post("/rooms/:roomId/join", async (request) => { const pathSegments = new URL(request.url).pathname.split("/") const roomId = pathSegments[2] return await live.room(roomId).join({ presence: { status: "online", typing: false, }, })})Send a message
Section titled “Send a message”app.post("/rooms/:roomId/messages", async (request) => { const pathSegments = new URL(request.url).pathname.split("/") const roomId = pathSegments[2] const body = await request.json()
return await live.room(roomId).publish({ type: "message.created", data: { body: body.body, }, idempotencyKey: body.clientMessageId, })})Update typing state
Section titled “Update typing state”app.post("/rooms/:roomId/typing", async (request) => { const pathSegments = new URL(request.url).pathname.split("/") const roomId = pathSegments[2] const body = await request.json()
return await live.room(roomId).presence({ presence: { status: "online", typing: Boolean(body.typing), }, })})List members
Section titled “List members”app.get("/rooms/:roomId/members", async (request) => { const pathSegments = new URL(request.url).pathname.split("/") const roomId = pathSegments[2] return Response.json({ members: await live.room(roomId).members({ limit: 100 }), })})Read history
Section titled “Read history”app.get("/rooms/:roomId/messages", async (request) => { const pathSegments = new URL(request.url).pathname.split("/") const roomId = pathSegments[2] const limit = Number(new URL(request.url).searchParams.get("limit") ?? 50) const cursor = new URL(request.url).searchParams.get("cursor") ?? undefined
return await live.room(roomId).history({ limit, cursor, })})