// supabase/functions/unsplash-search-photos/index.ts
serve(async (req) => {
try {
// 从环境变量中取得 Unsplash 存取金钥
const accessKey = Deno.env.get("SUPERUN_UNSPLASH_ACCESS_KEY");
if (!accessKey) {
return new Response(
JSON.stringify({ error: "Unsplash API key not configured" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
// 从请求中解析查询参数
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";
// 向 Unsplash API 发送请求
const unsplashUrl = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}`;
const response = await fetch(unsplashUrl, {
headers: {
"Authorization": `Client-ID ${accessKey}`,
},
});
if (!response.ok) {
throw new Error(`Unsplash API error: ${response.status}`);
}
const data = await response.json();
// 回传 Unsplash API 回应
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" } }
);
}
});