61 lines
2.0 KiB
TypeScript
61 lines
2.0 KiB
TypeScript
import { fetchEbayItems } from "@marketplace-scrapers/core";
|
|
|
|
/**
|
|
* GET /api/ebay?q={query}&minPrice={minPrice}&maxPrice={maxPrice}&strictMode={strictMode}&exclusions={exclusions}&keywords={keywords}&buyItNowOnly={buyItNowOnly}&canadaOnly={canadaOnly}
|
|
* Search eBay for listings (default: Buy It Now only, Canada only)
|
|
*/
|
|
export async function ebayRoute(req: Request): Promise<Response> {
|
|
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 },
|
|
);
|
|
|
|
// Parse optional parameters with defaults
|
|
const minPrice = reqUrl.searchParams.get("minPrice")
|
|
? parseInt(reqUrl.searchParams.get("minPrice")!)
|
|
: undefined;
|
|
const maxPrice = reqUrl.searchParams.get("maxPrice")
|
|
? parseInt(reqUrl.searchParams.get("maxPrice")!)
|
|
: undefined;
|
|
const strictMode = reqUrl.searchParams.get("strictMode") === "true";
|
|
const buyItNowOnly = reqUrl.searchParams.get("buyItNowOnly") !== "false";
|
|
const canadaOnly = reqUrl.searchParams.get("canadaOnly") !== "false";
|
|
const exclusionsParam = reqUrl.searchParams.get("exclusions");
|
|
const exclusions = exclusionsParam ? exclusionsParam.split(",").map(s => s.trim()) : [];
|
|
const keywordsParam = reqUrl.searchParams.get("keywords");
|
|
const keywords = keywordsParam ? keywordsParam.split(",").map(s => s.trim()) : [SEARCH_QUERY];
|
|
|
|
try {
|
|
const items = await fetchEbayItems(SEARCH_QUERY, 5, {
|
|
minPrice,
|
|
maxPrice,
|
|
strictMode,
|
|
exclusions,
|
|
keywords,
|
|
buyItNowOnly,
|
|
canadaOnly,
|
|
});
|
|
if (!items || items.length === 0)
|
|
return Response.json(
|
|
{ message: "Search didn't return any results!" },
|
|
{ status: 404 },
|
|
);
|
|
return Response.json(items, { status: 200 });
|
|
} catch (error) {
|
|
console.error("eBay scraping error:", error);
|
|
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
return Response.json(
|
|
{ message: errorMessage },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
}
|