@karnak19/fetcher
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

Fetcher

A tiny (less than 1kb) dead simple wrapper for Fetch API instance.

Installation

Install my-project with npm

  npm install @karnak19/fetcher

Usage/Examples

import { Fetcher } from "@karnak19/fetcher";

const myCoolApi = new Fetcher(process.env.MY_COOL_API_BASE_URL, {
  "x-cool-api-key": "myreallycooltoken",
});

You can defines function that will be invoked before every requests, and merged with the base headers you passed on constructor.

myCoolApi.onBefore([
  () => {
    return new Headers({
      "x-cool-api-key": "adefinitlybettertoken",
      // ^ This will override the default value
    });
  },
]);
const data = await myCoolApi.get<{ foo: string }>("/foo");

You can even add extra headers on a per-request basis

const data = await myCoolApi.get<{ foo: string }>(
  "/foo",
  new Headers({
    "x-cool-api-key": "nothisoneistheone",
    // ^ This will override headers defined on constructor AND onBefore hooks,
  })
);

API Reference

declare class Fetcher {
  constructor(baseUrl: string, headers: Headers);

  get<T>(url: string, headers: Headers): Promise<T>;
  post<T>(url: string, body: BodyInit, headers: Headers): Promise<T>;
  put<T>(url: string, body: BodyInit, headers: Headers): Promise<T>;
  delete<T>(url: string, body: BodyInit, headers: Headers): Promise<T>;

  onBefore(hooks: (() => Headers)[]): this;
}

Authors

Package Sidebar

Install

npm i @karnak19/fetcher

Weekly Downloads

67

Version

1.0.3

License

ISC

Unpacked Size

3.77 kB

Total Files

4

Last publish

Collaborators

  • bazeso