UNPKG

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