first commit
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const UNSPLASH_WALLPAPERS_URL =
|
||||
"https://api.unsplash.com/topics/wallpapers/photos";
|
||||
|
||||
const unsplashPhotoSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
slug: z.string().nullish(),
|
||||
description: z.string().nullish(),
|
||||
alt_description: z.string().nullish(),
|
||||
width: z.number().int().nullish(),
|
||||
height: z.number().int().nullish(),
|
||||
color: z.string().nullish(),
|
||||
blur_hash: z.string().nullish(),
|
||||
likes: z.number().int().nullish(),
|
||||
created_at: z.string().nullish(),
|
||||
updated_at: z.string().nullish(),
|
||||
urls: z.record(z.string(), z.unknown()).nullish(),
|
||||
links: z.record(z.string(), z.unknown()).nullish(),
|
||||
user: z.record(z.string(), z.unknown()).nullish(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type UnsplashPhoto = z.infer<typeof unsplashPhotoSchema>;
|
||||
|
||||
export async function fetchUnsplashWallpaperPhotos({
|
||||
page,
|
||||
perPage,
|
||||
}: {
|
||||
page: number;
|
||||
perPage: number;
|
||||
}) {
|
||||
const accessKey = process.env.UNSPLASH_ACCESS_KEY;
|
||||
|
||||
if (!accessKey) {
|
||||
throw new Error("UNSPLASH_ACCESS_KEY is not configured.");
|
||||
}
|
||||
|
||||
const url = new URL(UNSPLASH_WALLPAPERS_URL);
|
||||
url.searchParams.set("page", String(page));
|
||||
url.searchParams.set("per_page", String(perPage));
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
authorization: `Client-ID ${accessKey}`,
|
||||
"user-agent": "WalloraGallerySync/1.0",
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unsplash API request failed with ${response.status}.`);
|
||||
}
|
||||
|
||||
if (!contentType.includes("application/json")) {
|
||||
throw new Error(
|
||||
`Unsplash returned non-JSON content: ${contentType || "unknown"}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const payload = await response.json();
|
||||
const parsed = z.array(unsplashPhotoSchema).safeParse(payload);
|
||||
|
||||
if (!parsed.success) {
|
||||
throw new Error("Unsplash response did not match the expected array.");
|
||||
}
|
||||
|
||||
return parsed.data;
|
||||
}
|
||||
Reference in New Issue
Block a user