From d35e37f4c235586bf92a61894b6dbdade0caddea Mon Sep 17 00:00:00 2001 From: Dmytro Stanchiev Date: Wed, 17 Sep 2025 22:58:11 -0400 Subject: [PATCH] feat: implement Kijiji scraping API endpoint This commit introduces a new API endpoint that allows users to search for items on Kijiji. The endpoint accepts a search query as a header or query parameter and returns a JSON response containing the search results. It also handles cases where no query is provided or no results are found, returning appropriate error responses. --- src/index.ts | 54 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 3 deletions(-) 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}`);