diff --git a/src/index.ts b/src/index.ts index 60e340d..87bf95e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,54 @@ import fetchKijijiItems from "./kijiji"; -const SEARCH_QUERY = "playstation 5"; -const items = await fetchKijijiItems(SEARCH_QUERY); +const PORT = process.env.PORT || 4005; -console.log(items); +const server = Bun.serve({ + port: PORT, + idleTimeout: 0, + routes: { + // Static routes + "/api/status": new Response("OK"), + + // Dynamic routes + "/api/kijiji": async (req: Request) => { + const reqUrl = new URL(req.url); + + const SEARCH_QUERY = + req.headers.get("query") || reqUrl.searchParams.get("q") || null; + if (!SEARCH_QUERY) + return Response.json( + { + message: + "Request didn't have 'query' header or 'q' search parameter!", + }, + { status: 400 }, + ); + + const items = await fetchKijijiItems(SEARCH_QUERY); + if (!items) + return Response.json( + { message: "Search didn't return any results!" }, + { status: 404 }, + ); + return Response.json(items, { status: 200 }); + }, + + // Wildcard route for all routes that start with "/api/" and aren't otherwise matched + "/api/*": Response.json({ message: "Not found" }, { status: 404 }), + + // // Serve a file by buffering it in memory + // "/favicon.ico": new Response(await Bun.file("./favicon.ico").bytes(), { + // headers: { + // "Content-Type": "image/x-icon", + // }, + // }), + }, + + // (optional) fallback for unmatched routes: + // Required if Bun's version < 1.2.3 + fetch(req: Request) { + return new Response("Not Found", { status: 404 }); + }, +}); + +console.log(`Serving on ${server.hostname}:${server.port}`);