Skip to content

Please export the RequestInit interface #120

@0x80

Description

@0x80

I originally wrote this helper function for a project using node-fetch and I want to port it to unfetch, but I'm missing the RequestInit interface.

Without it I don't know how to type the options.

import fetch, { RequestInit } from "isomorphic-unfetch";
import { makeQueryString } from "../utils/query-string";

export async function fetchJson<T>(
  endpoint: string,
  queryParams: { [key: string]: string | number | boolean } = {},
  options: RequestInit = {}
): Promise<T> {
  const queryString = makeQueryString(queryParams);

  const url = `${endpoint}${queryString}`;

  const response = await fetch(url, {
    mode: "cors",
    ...options
  });

  if (!response.ok) {
    throw new Error(
      `Fetch to ${url} failed with status ${
        response.status
      }. Response text: ${await response.text()}`
    );
  }

  try {
    return response.json();
  } catch (err) {
    throw new Error(`Failed to parse JSON from response of ${url}`);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions