You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.4 KiB
43 lines
1.4 KiB
import fetch from 'node-fetch';
|
|
import PQueue from 'p-queue';
|
|
import { OmdbApiClient, OmdbResponse } from './types';
|
|
|
|
export const createOmdbApiClient = (apiKey: string): OmdbApiClient => {
|
|
// Rate limit (according to readme, it's 1k per day;
|
|
// here we set it 1 per second, should be enough for the demo app goal)
|
|
const queue = new PQueue({
|
|
interval: 1000,
|
|
intervalCap: 1,
|
|
timeout: 2000,
|
|
throwOnTimeout: true,
|
|
});
|
|
|
|
return {
|
|
fetchMetadata: async (imdbId: string) =>
|
|
queue.add(async () => {
|
|
const url = new URL('https://www.omdbapi.com/');
|
|
url.searchParams.append('i', imdbId);
|
|
url.searchParams.append('apikey', apiKey);
|
|
url.searchParams.append('plot', 'full');
|
|
|
|
const response = await fetch(url);
|
|
if (response.status == 404) {
|
|
return undefined;
|
|
}
|
|
|
|
const body = (await response.json()) as OmdbResponse;
|
|
if (body.Response !== 'True') {
|
|
if (body.Error === 'Incorrect IMDb ID.') {
|
|
return undefined;
|
|
}
|
|
|
|
throw new Error(
|
|
`Cannot fetch data from OMDB: ${body.Error}`,
|
|
);
|
|
}
|
|
|
|
const { Response: _status, ...rawOmdbData } = body;
|
|
return rawOmdbData;
|
|
}),
|
|
};
|
|
};
|
|
|