47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import { fetchFacebookItems } from "@marketplace-scrapers/core";
|
|
|
|
/**
|
|
* GET /api/facebook?q={query}&location={location}&cookies={cookies}
|
|
* Search Facebook Marketplace for listings
|
|
*/
|
|
export async function facebookRoute(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 },
|
|
);
|
|
|
|
const LOCATION = reqUrl.searchParams.get("location") || "toronto";
|
|
const COOKIES_SOURCE = reqUrl.searchParams.get("cookies") || undefined;
|
|
const maxItemsParam = reqUrl.searchParams.get("maxItems");
|
|
const maxItems = maxItemsParam ? parseInt(maxItemsParam, 10) : 25;
|
|
|
|
try {
|
|
const items = await fetchFacebookItems(
|
|
SEARCH_QUERY,
|
|
1,
|
|
LOCATION,
|
|
maxItems,
|
|
COOKIES_SOURCE,
|
|
undefined,
|
|
);
|
|
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("Facebook scraping error:", error);
|
|
const errorMessage =
|
|
error instanceof Error ? error.message : "Unknown error occurred";
|
|
return Response.json({ message: errorMessage }, { status: 400 });
|
|
}
|
|
}
|