Skip to content

Chat room

This example creates a small chat API with join, publish, presence, members, and history routes.

Terminal window
import { backend } from "@layeron/core"
import { realtime } from "@layeron/modules"
const app = backend()
const live = realtime({
name: "chat",
historyLimit: 100,
})
app.use(live)
Terminal window
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,
},
})
})
Terminal window
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,
})
})
Terminal window
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),
},
})
})
Terminal window
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 }),
})
})
Terminal window
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,
})
})