// supabase/functions/pexels-search-photos/index.ts
serve(async (req) => {
try {
// Get the Pexels API Key from environment
const apiKey = Deno.env.get("SUPERUN_PEXELS_ACCESS_KEY");
if (!apiKey) {
return new Response(
JSON.stringify({ error: "Pexels API key not configured" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
// Parse query parameters from the request
const url = new URL(req.url);
const query = url.searchParams.get("query");
if (!query) {
return new Response(
JSON.stringify({ error: "query is empty" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
const page = url.searchParams.get("page") || "1";
const perPage = url.searchParams.get("per_page") || "10";
const color = url.searchParams.get("color");
const orientation = url.searchParams.get("orientation");
// Build query parameters
const params = new URLSearchParams({
query: query,
page: page,
per_page: perPage,
});
if (color) {
params.append("color", color);
}
if (orientation) {
params.append("orientation", orientation);
}
// Make request to Pexels API
const pexelsUrl = `https://api.pexels.com/v1/search?${params.toString()}`;
const response = await fetch(pexelsUrl, {
headers: {
"Authorization": apiKey,
},
});
if (!response.ok) {
throw new Error(`Pexels API error: ${response.status}`);
}
const data = await response.json();
// Return the Pexels API response
return new Response(
JSON.stringify(data),
{
headers: { "Content-Type": "application/json" },
}
);
} catch (error) {
return new Response(
JSON.stringify({ error: error.message }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
});