// A small test server for this lesson, made with node:http. You do not need to change it.
import {createServer} from "node:http";
const TITLES = ["Dune", "Emma", "Kindred", "Beloved"];
export async function startServer() {
const server = createServer((request, response) => {
const url = new URL(request.url, "http://localhost");
const json = (status, value) => {
response.writeHead(status, {"Content-Type": "application/json"});
response.end(JSON.stringify(value));
};
const later = (ms, value) => {
const timer = setTimeout(() => json(200, value), ms);
response.on("close", () => clearTimeout(timer)); // the client gave up
};
if (url.pathname === "/books/1") json(200, {id: 1, title: "Dune"});
else if (url.pathname === "/slow") later(300, {id: 3, title: "Kindred"});
else if (url.pathname === "/search") {
// the titles that contain ?q=…, after 50 ms
const term = (url.searchParams.get("q") ?? "").toLowerCase();
later(50, TITLES.filter((title) => title.toLowerCase().includes(term)));
} 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}`,
close: () => new Promise((resolve) => server.close(resolve))
};
}