Build the Shared TMDB Request Helper
Build the Shared TMDB Request Helper
Now turn the configuration into a reusable request function. Every later TMDB function should be able to provide a path and a small set of query parameters without rebuilding the URL or error handling.
Step 1 — Build the URL from the base
Still in lib/tmdb.ts, create tmdbFetch and construct a URL from TMDB_BASE and the supplied path.
async function tmdbFetch(path: string, params: Record<string, string> = {}) {
const url = new URL(TMDB_BASE + path);
Step 2 — Add authentication and language
Set the common query parameters first.
url.searchParams.set("api_key", apiKey());
url.searchParams.set("language", "en-US");
Then loop over the optional parameters and add only values that are present.
for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== "") url.searchParams.set(k, v);
}
Step 3 — Fetch and fail clearly
Use fetch with the existing five-minute revalidation behavior from the final project.
const res = await fetch(url.toString(), {
next: { revalidate: 300 },
});
If the response is not successful, read the response body and throw an error that includes the HTTP status. That gives the UI a useful failure message instead of silently returning bad data.
Checkpoint
tmdbFetch can build a complete TMDB request and reject unsuccessful responses with a readable error. Nothing in the UI changes yet; the next lesson will add the first public data functions.