Options
All
  • Public
  • Public/Protected
  • All
Menu

WHATWG Fetch Extension

Provides an extension to the WHATWG fetch API to allow for TypeScript verification and conversion of JSON responses.

Usage

import { Json, isIJsonObject } from '@ef-carbon/fetch';
import { fetcher } from '@ef-carbon/fetcher';

interface IData {
  name: string;
}

function isIData(json: Json): json is IData {
  return isIJsonObject(json) && typeof json.name === 'string';
}

function getName(json: Json): string {
  if (!isIData(json)) {
    throw TypeError(`Invalid JSON payload: ${JSON.stringify(json)}`);
  }

  return json.name;
}

// expected payload `{ "name": "@ef-carbon/fetcher", ... }`
const response = await fetcher('https://raw.githubusercontent.com/ef-carbon/fetcher/master/package.json');

const data = response.json(isIData);  // verification
console.log(data.name);

const name = response.json(getName);  // conversion
console.log(name);

For more information see the fetcher API documentation.