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

browser-http-client

v3.2.0

Published

Lightweight, browser-specific, strongly typed XHR client.

Downloads

7

Readme

browser-http-client

npm npm downloads GitHub issues GitHub stars GitHub license

A lightweight, browser-specific, strongly typed XHR client. Meant for usage with TypeScript.

# npm 5 and up saves deps by default
npm i browser-http-client

# alternately with yarn
yarn add browser-http-client

v3.x

Version 3 adds an opinionated twist to doing ajax. All requests now return a wrapper type known as a Result. A Result type holds either an Ok<T> or an Err<E> (where T and E are generic type variables that hold the type of whatever you're wrapping). Thanks to the safe-types lib, the Result comes with many methods that allow perform operations of the Ok and Err values with safety because it matches the case under the hood and provides type-safe control flow.

This change to using result types can simplify the successful path for our programs, as well as provide consistency for the error states our program can exist in. Given that an XHR can error in a number of ways, the pseudo pattern match available on the ClientError type makes declaratively handling all those possibilities much easier.

Purpose

Modern web applications require extensive use of ajax calls, but for basic CRUD operations, the calls are fairly simple. Feature rich clients like $.ajax, axios and superagent offer very nice APIs, but many of their features go unused. It's also very common for ajax clients to support both browser and server in the same package. All this means shipping unnecessary code to our end users.

This library is modeled after familiar client APIs, but in a no-frills manner. It's a basic XHR client for the browser only, while still providing a convenient abstraction for the 80% use-case of ajax requests. It's written in TypeScript to help provide a stable package as well as a better development experience when consuming its APIs. Many of the hacks to support older browsers have been dropped in favor of an >=ES5 compatible codebase

  • Note: a compatibility check is performed when the lib is loaded, and an Error will be logged if required browser APIs are not present (thrown if window.onerror is defined, logged otherwise).

Much of the code is adapted from the axios client. While it isn't a drop-in replacement for axios, the APIs and data structures are very similar. If you choose to build your application using this package, then decide to upgrade to axios in the future, the similarities will make refactoring relatively easy.

Usage

browser-http-client has a dependency on safe-types and is built for ESM only.

*Note: TypeScript users can dig into the package to access an enum/map of Http status codes as registered with IANA. This is not part of the default build as it requires your build tooling to compile from source.

import { Status } from "browser-http-client/src/xhr/status.ts";

Example

import { Client } from "browser-http-client";

Client.get("https://api.github.com/users/alexsasharegan/repos").then(result =>
  result.match({
    Ok: ({ headers, status, statusText, data }) => {
      console.log("Response headers:", headers);
      console.log(`Response status: ${statusText} [${status}]`);
      console.log("Response data:", data);
    },
    // The error value has a discriminant prop called `type` that allows for explicit error shape inference.
    // For example, XhrErr will contain the response, Abort will not, and Timeout
    // specifically receives the ProgressEvent type instead of the generic Event.
    // The error type is also imbued with a pseudo pattern matching method
    Err: err => err.match({
      HttpStatusErr: statusErr => console.error(statusErr.response.data),
      XhrErr: err => console.error(err.event),
      Timeout: console.error,
      Abort: console.error,
    })
  })
);

// url: string, data?: object, options?: object
Client.post("/api/got/characters", {
  first_name: "John",
  last_name: "Snow",
  house: ["Stark", "Targaryen"],
});

// url: string, query?: object
Client.get("/api/got/characters", {
  last_name: "Snow",
  house: ["Stark", "Targaryen"],
});
// URL generated:
// - https://developer.github.com/api/got/characters?last_name=Snow&house[]=Stark&house[]=Targaryen
// * Note: undefined values are omitted from query strings.