UNPKG

1.14 kBPlain TextView Raw
1import { npmRegistry, npmRegistryMirrors } from '../data/registries';
2import { FetchError } from './errors';
3import { fetch } from './fetch';
4import { log } from './log';
5
6export async function fetchFromRegistry<T>({
7 endpoint,
8 query,
9 registry = npmRegistry,
10 mirrors = npmRegistryMirrors,
11 cached,
12}: {
13 endpoint: string;
14 query?: string;
15 registry?: string;
16 mirrors?: string[];
17 cached?: boolean;
18}): Promise<T> {
19 const urls = [registry, ...mirrors].map((host) => {
20 const url = new URL(endpoint, host);
21 url.search = query ?? '';
22 return url.href;
23 });
24
25 let lastError: FetchError | undefined;
26 for (const url of urls) {
27 try {
28 const json = await fetch({ url, cached });
29 return json as T;
30 } catch (err) {
31 // Keep last fetch error
32 lastError = err;
33 }
34 }
35
36 log(
37 'fetchFromRegistry: cannot retrieve data from registry or mirrors: %O',
38 {
39 endpoint,
40 query,
41 registry,
42 mirrors,
43 lastError,
44 }
45 );
46 throw lastError;
47}