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