-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.sx
More file actions
52 lines (41 loc) · 1.66 KB
/
Copy pathserver.sx
File metadata and controls
52 lines (41 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// An HTTP server. Run it: sxn examples/server.sx
//
// The handler takes a Request and returns a Response, the same two objects a
// handler on Cloudflare Workers, Deno or Bun receives. `port: 0` asks the OS
// for a free port; pass a real one to pick it yourself.
interface Note {
id: number;
text: string;
}
const notes: Map<number, string> = new Map([[1, "the first note"]]);
let mut nextId: number = 2;
const server = Sxn.serve({ port: 0 }, async (req: Request): Promise<Response> => {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("try /notes");
}
if (url.pathname === "/notes" && req.method === "GET") {
const all: Note[] = [...notes].map(([id, text]) => ({ id, text }));
return Response.json(all);
}
if (url.pathname === "/notes" && req.method === "POST") {
const { text } = await req.json();
const note: Note = { id: nextId++, text };
notes.set(note.id, note.text);
return Response.json(note, { status: 201 });
}
return new Response("not found", { status: 404 });
});
console.log(`listening on ${server.url}`);
// Call the server we just started, from the same process.
const created = await fetch(`${server.url}/notes`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ text: "written by the example" }),
});
console.log("POST /notes ->", created.status, await created.text());
const all = await fetch(`${server.url}/notes`);
console.log("GET /notes ->", all.status, await all.text());
// Without stop() the listening socket keeps the process alive, which is what
// you want for a real server and not for a script that has finished.
server.stop();