npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fetch-toolkit

v0.1.9

Published

Fetch API Toolkit for increased productivity

Downloads

15

Readme

Coverage

fetch-toolkit

Fetch API Toolkit for increased productivity.

Highlights

  • Handles common fetch error handling, HTTP status and pitfalls
  • Implement API calls easily
  • Extensible via decorators. Out-of-the box decorators:
    • Authentication
    • Logging
    • Concurrency limit/throttling

Installation

npm install fetch-toolkit -s

Using fetch with node.js version smaller than 18

If you are running your application in the browser or node 18 or greater, you are all set. If you are running it with a version of node smaller than 18, you need to install some fetch API implementation. Example:

npm install node-fetch -s

API Reference

For full API Reference check here

Basic Usage

Making simple REST API calls

The fetchJson function is just a helper function, that will save something like 3 to 5 lines of code. Apart from doing a remote call, it:

  1. Converts the result from JSON to a Javascript object
  2. Throws FetchErrors in case of failure
  3. Tries to get the response even in case of errors as some APIs return an error object along with failure status codes
import { fetchJson } from "fetch-toolkit";

function myCall: Promise<Myresult> {   
  return fetchJson("https://example.com/rest/get");
}

Implementing an API

To implement an API, create a new class that extends the API class. Create a function for each API method. The query and post parameters are automatically serialized to the URL or to the post body respectively. If using typescript, you can use strong-types for the request and response objects.

import { API } from "fetch-toolkit";

export type Item {
  id: string;
  name: string;
}

export type PaginationParams {
  "max-items": number | undefined;
  "start-index": number | undefined;
}

export class MyApi extends API {

  getAllItems(pagination: PaginationParams): Promise<Item> {
    return this.get<Item>(`/api/latest/items`, pagination);
  }

  getItem(id: string): Promise<Item> {
    return this.get<Item>(`/api/latest/items/${id}`);
  }

  updateItem(id: string, item: Item): Promise<void> {
    return this.post<void>(`/api/latest/items/${id}`, item);
  }
}

Adding authentication

To add authentication to the API, just select a suitable authentication provider or implent your custom one. fetch-toolkit currently implements the BasicAuthenticationProvider and BearerAutheticationProvider

import { API, BasicAuthenticationProvider } from "fetch-toolkit";

export class MyApi extends API {

  constructor(baseUrl: string, username: string, password: string) {
    super(baseUrl, new BasicAuthenticationProvider(username, password));
  }

  ...
}

Limiting the number of parallel calls

APIs often impose limits on the number of calls a client can make. To avoid exceeding this limit, you can configure the maxParallel parameter when setting up the API. This parameter sets an upper limit on the number of concurrent API calls. Once this limit is reached, any additional calls will be queued and processed once the ongoing calls finish.

import { API, BasicAuthenticationProvider } from "fetch-toolkit";

export class MyApi extends API {

  constructor(baseUrl: string, username: string, password: string) {
    super(baseUrl, new BasicAuthenticationProvider(username, password), 2);
  }

  ...
}

Logging the API calls

For debug purposes, you can log all the API calls. Currently only the FetchConsoleLogger is available which logs the requests to the console. But you can implement your own logger by extending the FetchLogger class.

import { API, BearerAuthenticationProvider, FetchConsoleLogger } from "fetch-toolkit";

export class MyApi extends API {
    constructor(readonly baseUrl: string, readonly authToken: string) {
        super(baseUrl, new BearerAuthenticationProvider(authToken), 2, new FetchConsoleLogger());
    }

    ...
}