diff --git a/packages/cli/src/helpers/registry.ts b/packages/cli/src/helpers/registry.ts index 404ec2c..efd370c 100644 --- a/packages/cli/src/helpers/registry.ts +++ b/packages/cli/src/helpers/registry.ts @@ -1,14 +1,13 @@ -import fetch from 'node-fetch' - import {REGISTRY_URL, Registry} from '../const.js' +import {safeFetch} from './safeFetcher.js' export async function getRegistry( branch?: string, ): Promise<{message: string; ok: false} | {ok: true; registry: Registry}> { - const registryResponse = await fetch(REGISTRY_URL(branch ?? 'main')) + const registryResponse = await safeFetch(REGISTRY_URL(branch ?? 'main')) if (registryResponse.ok) { - const registryJson = (await registryResponse.json()) as Registry + const registryJson = registryResponse.json as Registry registryJson.base = registryJson.base.replace('{branch}', branch ?? 'main') return { @@ -17,10 +16,7 @@ export async function getRegistry( } } - return { - message: `Error while fetching registry from ${registryResponse.url}: ${registryResponse.status} ${registryResponse.statusText}`, - ok: false, - } + return registryResponse } export async function getAvailableComponentNames(registry: Registry): Promise { diff --git a/packages/cli/src/helpers/safeFetcher.ts b/packages/cli/src/helpers/safeFetcher.ts new file mode 100644 index 0000000..7f63d5b --- /dev/null +++ b/packages/cli/src/helpers/safeFetcher.ts @@ -0,0 +1,19 @@ +import fetch, {Response} from 'node-fetch' + +export async function safeFetch( + url: string, +): Promise<{ok: true; json: unknown} | {ok: false; message: string; response: Response}> { + const response = await fetch(url) + if (response.ok) { + return { + ok: true, + json: await response.json(), + } + } + + return { + ok: false, + message: `Error while fetching from ${response.url}: ${response.status} ${response.statusText}`, + response, + } +}