async function callApi(url: string, key: string) {
const response = await fetch(url, {
headers: { Authorization: `Bearer ${key}` },
});
if (!response.ok) {
const { error } = await response.json();
switch (error.code) {
case "unauthorized":
throw new Error("Check your API key");
case "forbidden":
throw new Error(`Missing scope for ${url}`);
case "rate_limited":
const retryAfter = response.headers.get("Retry-After");
throw new Error(`Rate limited — retry in ${retryAfter}s`);
case "not_found":
return null; // treat as empty, not fatal
default:
throw new Error(`API error: ${error.message}`);
}
}
return response.json();
}