Rebasely Beta: data may be purged

examples/live-notes Public

TypeScript · 30 lines · 1.2 KiB · at 4343feb

// The live-notes Worker. It routes each note to its own NoteRoom by name, so every editor of// "groceries" reaches the same object wherever they are.////   GET /notes/:id      the note as JSON: { id, text, version }//   GET /notes/:id/ws   upgrade to a WebSocket and edit the note (protocol.ts)import type { NoteRoom } from "./note-room.ts";import { route } from "./routes.ts";export { NoteRoom } from "./note-room.ts";export interface Env {  NOTES: DurableObjectNamespace<NoteRoom>;}export default {  async fetch(request, env): Promise<Response> {    const r = route(new URL(request.url).pathname);    if (!r) return new Response("not found", { status: 404 });    if (request.method !== "GET") return new Response("method not allowed", { status: 405, headers: { allow: "GET" } });    const room = env.NOTES.get(env.NOTES.idFromName(r.id));    if (r.kind === "socket") {      if (request.headers.get("Upgrade") !== "websocket") return new Response("expected a WebSocket upgrade", { status: 426 });      return room.fetch(request);    }    const note = await room.read();    return Response.json({ id: r.id, text: note.text, version: note.version });  },} satisfies ExportedHandler<Env>;