feat: fallback to unsplash cover when article contains no image
This commit is contained in:
29
lib/unsplash.ts
Normal file
29
lib/unsplash.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { UNSPLASH_API_KEY } from "./env.ts";
|
||||
|
||||
const API_URL = "https://api.unsplash.com";
|
||||
|
||||
export async function getImageBySearchTerm(
|
||||
searchTerm: string,
|
||||
): Promise<string | undefined> {
|
||||
if (!UNSPLASH_API_KEY) {
|
||||
throw new Error("UNSPLASH_API_KEY is not set");
|
||||
}
|
||||
|
||||
const url = new URL("/search/photos", API_URL);
|
||||
url.searchParams.append("query", searchTerm);
|
||||
url.searchParams.append("per_page", "1");
|
||||
url.searchParams.append("orientation", "landscape");
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
headers: {
|
||||
Authorization: `Client-ID ${UNSPLASH_API_KEY}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unsplash API request failed: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.results[0]?.urls?.regular;
|
||||
}
|
||||
Reference in New Issue
Block a user