// A small test server for this lesson, made with node:http. You do not need to change it.
import {createServer} from "node:http";
export async function startServer() {
const counts = {}; // how often each path was requested
const server = createServer((request, response) => {
const path = request.url;
counts[path] = (counts[path] ?? 0) + 1;
const send = (status, type, text) => {
response.writeHead(status, {"Content-Type": type});
response.end(text);
};
const json = (status, value) => send(status, "application/json", JSON.stringify(value));
if (path === "/books/1") json(200, {id: 1, title: "Dune"});
else if (path === "/broken") send(500, "text/plain", "Server error");
else if (path === "/flaky") {
// busy twice (503), then it works
if (counts[path] <= 2) send(503, "text/plain", "Busy");
else json(200, {id: 2, title: "Emma"});
} else if (path === "/html") send(200, "text/html", "<h1>Down for maintenance</h1>");
else if (path === "/slow") {
// answers after 300 ms, unless the client gave up
const timer = setTimeout(() => json(200, {id: 3, title: "Kindred"}), 300);
response.on("close", () => clearTimeout(timer));
} else json(404, {error: "Not found"});
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); // port 0: any free port
return {
url: `http://127.0.0.1:${server.address().port}`,
count: (path) => counts[path] ?? 0,
close: () => new Promise((resolve) => server.close(resolve))
};
}