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.
This commit is contained in:
54
src/index.ts
54
src/index.ts
@@ -1,6 +1,54 @@
|
|||||||
import fetchKijijiItems from "./kijiji";
|
import fetchKijijiItems from "./kijiji";
|
||||||
|
|
||||||
const SEARCH_QUERY = "playstation 5";
|
const PORT = process.env.PORT || 4005;
|
||||||
const items = await fetchKijijiItems(SEARCH_QUERY);
|
|
||||||
|
|
||||||
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}`);
|
||||||
|
|||||||
Reference in New Issue
Block a user