|
| 1 | +import http from "node:http"; |
| 2 | + |
| 3 | +const port = Number(process.env.PORT ?? 4010); |
| 4 | +const delayMs = Number(process.env.FAKE_GNEWS_DELAY_MS ?? 0); |
| 5 | + |
| 6 | +function articleFor(query, index) { |
| 7 | + return { |
| 8 | + title: `${query} headline ${index + 1}`, |
| 9 | + description: `Synthetic article ${index + 1} for ${query}`, |
| 10 | + content: `Synthetic content for ${query}`, |
| 11 | + url: `https://example.test/news/${encodeURIComponent(query)}/${index + 1}`, |
| 12 | + image: null, |
| 13 | + publishedAt: "2026-01-01T00:00:00.000Z", |
| 14 | + source: { |
| 15 | + name: "CI News", |
| 16 | + url: "https://example.test", |
| 17 | + }, |
| 18 | + }; |
| 19 | +} |
| 20 | + |
| 21 | +function sendJson(res, status, body) { |
| 22 | + res.writeHead(status, { "content-type": "application/json" }); |
| 23 | + res.end(JSON.stringify(body)); |
| 24 | +} |
| 25 | + |
| 26 | +const server = http.createServer((req, res) => { |
| 27 | + const url = new URL(req.url ?? "/", "http://127.0.0.1"); |
| 28 | + |
| 29 | + if (url.pathname === "/health") { |
| 30 | + sendJson(res, 200, { status: "ok" }); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + if (url.pathname !== "/search") { |
| 35 | + sendJson(res, 404, { error: "not found" }); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + const query = url.searchParams.get("q") ?? "news"; |
| 40 | + const count = Math.max(1, Math.min(Number(url.searchParams.get("max") ?? 3), 100)); |
| 41 | + const articles = Array.from({ length: count }, (_, index) => articleFor(query, index)); |
| 42 | + |
| 43 | + setTimeout(() => sendJson(res, 200, { articles }), delayMs); |
| 44 | +}); |
| 45 | + |
| 46 | +server.listen(port, "0.0.0.0", () => { |
| 47 | + console.log(`fake GNews provider listening on ${port}`); |
| 48 | +}); |
| 49 | + |
| 50 | +process.on("SIGTERM", () => { |
| 51 | + server.close(() => process.exit(0)); |
| 52 | +}); |
0 commit comments