Fall back to OMDb demo on rate limits
This commit is contained in:
1 parent
4f78883f0b
commit
dfe3955604
2 files changed
+28
-5
No files matched your search
+13
-2
@@ -4,6 +4,9 @@ import type { MediaDetails } from '#lib/media/types';
|
||||
const cacheDuration = 24 * 60 * 60 * 1000;
|
||||
const imdbIdPattern = /tt\d+/;
|
||||
const missingValue = 'N/A';
|
||||
const omdbUrl = 'https://www.omdbapi.com/';
|
||||
const omdbDemoUrl = 'http://www.omdbapi.com/demo.aspx/';
|
||||
const rateLimitedStatus = 401;
|
||||
|
||||
interface OmdbResponse {
|
||||
Response: 'True' | 'False';
|
||||
@@ -35,13 +38,21 @@ function toMediaDetails(result: OmdbResponse): MediaDetails {
|
||||
};
|
||||
}
|
||||
|
||||
async function requestOmdb(imdbId: string): Promise<Response> {
|
||||
const params = new URLSearchParams({ apikey: OMDB_API_KEY ?? '', i: imdbId, plot: 'short' });
|
||||
const response = await fetch(`${omdbUrl}?${params}`);
|
||||
if (response.status !== rateLimitedStatus) return response;
|
||||
|
||||
const demoParams = new URLSearchParams({ i: imdbId, token: 'demo' });
|
||||
return fetch(`${omdbDemoUrl}?${demoParams}`);
|
||||
}
|
||||
|
||||
async function fetchDetails(imdbId: string): Promise<MediaDetails | null> {
|
||||
const cached = detailsCache.get(imdbId);
|
||||
if (cached && Date.now() - cached.fetchedAt < cacheDuration) return cached.details;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({ apikey: OMDB_API_KEY ?? '', i: imdbId, plot: 'short' });
|
||||
const response = await fetch(`https://www.omdbapi.com/?${params}`);
|
||||
const response = await requestOmdb(imdbId);
|
||||
if (!response.ok) throw new Error(`OMDb returned ${response.status}`);
|
||||
|
||||
const result: OmdbResponse = await response.json();
|
||||
|
||||
Reference in new issue
Block a user