Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface IMutable

Extends the native body interface to have a json method that accepts verification and conversion functions

example

Perform verification of JSON payload

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

interface IData {
  name: string;
}

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

const verify: Verify<IData> = isIData;

// expected payload `{ "name": "Rick Sanchez" }`
const response = await fetcher('http://endpoint.com/data.json');

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

Perform conversion of JSON payload

import { Json, isIJsonObject } from '@ef-carbon/fetch';
import { fetcher, Convert } 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;
}

const convert: Convert<string> = getName;

// expected payload `{ "name": "Rick Sanchez" }`
const response = await fetcher('http://endpoint.com/data.json');

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

Verify

see

Convert

Hierarchy

Index

Properties

Methods

Properties

bodyUsed

bodyUsed: boolean

Methods

arrayBuffer

  • arrayBuffer(): Promise<ArrayBuffer>
  • Returns Promise<ArrayBuffer>

json

  • json<T>(callback: Convert<T>): Promise<T>
  • json<T>(verify: Verify<T>): Promise<T>
  • json(): Promise<Json>
  • Performs the conversion of the JSON

    Type parameters

    • T: any | number | string

    Parameters

    • callback: Convert<T>

      the conversion function

    Returns Promise<T>

    the converted JSON as the correct JavaScript/TypeScript object, number or string

  • Performs the verification of the JSON

    Type parameters

    • T

    Parameters

    Returns Promise<T>

    the verifed JSON casted to the correct TypeScript interface

  • Retrieves the JSON from the response, just as the native Response.json does

    Returns Promise<Json>

    the response as JSON

text

  • text(): Promise<string>
  • Returns Promise<string>