All files / kernel-utils/src fetchValidatedJson.ts

100% Statements 8/8
100% Branches 2/2
100% Functions 1/1
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31                            3x 3x 3x 1x       2x 2x 2x   2x          
import type { Struct } from '@metamask/superstruct';
import { assert } from '@metamask/superstruct';
 
/**
 * Load and validate a JSON file
 *
 * @param configUrl - Path to the JSON file
 * @param validator - The validator to use to validate the JSON
 * @returns The validated JSON
 */
export async function fetchValidatedJson<Type>(
  configUrl: string,
  validator: Struct<Type>,
): Promise<Type> {
  try {
    const response = await fetch(configUrl);
    if (!response.ok) {
      throw new Error(
        `Failed to fetch config: ${response.status} ${response.statusText}`,
      );
    }
    const config = await response.json();
    assert(config, validator);
    return config;
  } catch (error) {
    throw new Error(
      `Failed to load config from ${configUrl}: ${String(error)}`,
    );
  }
}