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

@wolfpackthatcodes/http-client

v0.7.1

Published

An expressive, minimal wrapper around the Fetch() API allowing you to quickly make HTTP requests.

Downloads

17

Readme


About

HTTP Client is an expressive, minimal wrapper around the Fetch() API allowing you to quickly make HTTP requests. The HTTP Client utilizes the Builder creational design pattern to provide descriptive methods to construct your Fetch API request.

Disclaimer

Until HTTP Client reaches a 1.0.0 release, breaking changes will be released with a new minor version.

Getting Started

You will need to make sure your system meets the following prerequisites:

  • Node.js >= 18.0.0

Package installation

You can install HTTP Client from npm registry or GitHub Packages.

npm install @wolfpackthatcodes/http-client

To install HTTP Client from GitHub Packages, follow the steps in the GitHub documentation for installing a package.

How To Use

This project is a work-in-progress. Code and documentation are currently under development and are subject to change.

Documentation on the available functionality has been outlined below for you to get started:

Since the HTTP Client is a wrapper for Fetch() API, you can still make HEAD, GET, POST, PUT, PATCH, DELETE requests using the respectively helper methods provided.

All request helper methods return a promise that resolves with a Response object.

Send a HEAD request.

Let's see how to make a basic HEAD request to another URL:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient().head('https://api.example.local');
Send a OPTIONS request.

Let's see how to make a basic OPTIONS request to another URL:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient().options('https://api.example.local');
Send a GET request.

Let's see how to make a basic GET request to another URL:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient().get('https://api.example.local/users');
Send a GET request with query parameters

When making GET requests, you may either append a query string to the URL directly or pass an object of key / value pairs as the second argument to the get method:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .get('https://api.example.local/users', { page: 1, limit: 10 });

Alternatively, the withQueryParameters method may be used:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .withQueryParameters({ page: 1, limit: 10 })
  .get('https://api.example.local/users');

You can send additional data with your POST, PUT, and PATCH requests. These methods accept either a string or an object of data as their second argument.

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .post('https://api.example.local/users/1/notes', 'Example text.');

By default, data will be sent with a header of Content-Type: text/plain.

Send data as JSON

If you would like to send data using the application/json content type, you can use the asJson method before making your request:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .asJson()
  .patch('https://api.example.local/users/1', { first_name: 'Luis', last_name: 'Aveiro' });
Send data as URLSearchParams

If you would like to send data using the application/x-www-form-urlencoded content type, you can use the asUrlEncoded method before making your request:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .asUrlEncoded()
  .put('https://api.example.local/users/1', { first_name: 'Luis', last_name: 'Aveiro' });
Send data as FormData

If you would like to send data using the multipart/form-data content type, you can use the asForm method before making your request:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .asForm()
  .post('https://api.example.local/users', { first_name: 'Luis', last_name: 'Aveiro' });

You can add multiple headers to the request by using the withHeaders method. The withHeaders method accepts an object of key / value pairs or Headers instance:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const headers = {
    'X-Header': 'value',
    'Y-Header': 'value',
};

const firstResponse = new HttpClient()
  .withHeaders(headers)
  .get('https://api.example.local/users');

const secondResponse = new HttpClient()
  .withHeaders(new Headers(headers))
  .get('https://api.example.local/posts');

Alternatively, use withHeader method to include an individual header.

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .withHeader('X-Header', 'value')
  .get('https://api.example.local/users');
Replace headers

The replaceHeaders method allow you to replace multiple headers. The replaceHeaders method accepts an object of key / value pairs or Headers instance:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const httpClient = new HttpClient()
  .withHeaders({ 'Content-Type': 'application/xml', Accept: 'application/html' });

const updatedHeaders = {
  'Content-Type': 'application/json',
  Accept: 'application/json'
};

const firstResponse = httpClient
  .replaceHeaders(updatedHeaders)
  .get('https://api.example.local/users');

const secondResponse = httpClient
  .replaceHeaders(new Headers(updatedHeaders))
  .get('https://api.example.local/users');

Alternatively, use replaceHeader method to replace individual header.

import { HttpClient } from '@wolfpackthatcodes/http-client';

const httpClient = new HttpClient()
  .withHeaders({ 'Content-Type': 'application/xml', Accept: 'application/html' });

const response = httpClient
  .replaceHeader('Content-Type', 'application/json')
  .get('https://api.example.local/users');
Define content type accepted

You may use the accept method to specify the content type that your application is expecting in response to your request:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .accept('application/json')
  .get('https://api.example.local/users');

You may use the acceptJson method to quickly specify that your application expects the application/json content type in response to your request:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .acceptJson()
  .get('https://api.example.local/users');

You may specify basic authentication credentials using the withBasicAuth and method.

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient().withBasicAuth('luisaveiro', 'secret').get('https://api.example.local/settings');
Bearer Tokens

If you would like to quickly add a bearer token to the request's Authorization header, you may use the withToken method:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient().withToken('your-token').get('https://api.example.local/settings');

You may specify additional Fetch() API Request options using the withOptions method. The withOptions method accepts an object of key / value pairs:

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .withOptions({ 
    credentials: 'same-origin',
    mode: 'same-origin' 
  })
  .get('https://api.example.local/users');

Alternatively, use withOption method to include an individual option.

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .withOption('credentials', 'same-origin')
  .get('https://api.example.local/users');

The HTTP Clients offers a retry method to retry the request automatically if the request attempt fails.

The retry method specifies the maximum number of attempts, the interval in milliseconds between attempts, and an optional callback function to determine whether a retry should be attempted based on the response, the request and the error instance.

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .retry(3, 1000, (response, request, error) => {
    return response !== undefined && response.status !== 404;
  })
  .get('https://api.example.local/test/');

The HTTP Clients offers a timeout method to specify the maximum number of milliseconds to wait for a response.

The timeout method accepts the maximum number of milliseconds the request should wait for a response.

import { HttpClient } from '@wolfpackthatcodes/http-client';

const response = new HttpClient()
  .timeout(1000)
  .get('https://api.example.local/test/');

The HTTP Client offers a fake method that allows you to instruct the HTTP Client to return mocked responses when requests are made. The fake method will prevent the HTTP Client to make a HTTP request.

import { HttpClient } from '@wolfpackthatcodes/http-client';

interface User {
  id: number;
  name: string;
  email: string;
}

function createUserArray(): User[] {
  const users: User[] = [
    { id: 1, name: 'John Doe', email: '[email protected]' },
    { id: 2, name: 'Jane Smith', email: '[email protected]' },
    { id: 3, name: 'Alice Johnson', email: '[email protected]' },
    // Add more user objects as needed
  ];

  return users;
}

const mockedResponse = new Response(
  JSON.stringify(createUserArray()),
  { status: 200, headers: new Headers({ 'Content-Type': 'application/json' }) }
);

const response = new HttpClient()
  .fake('https://api.example.local/users', mockedResponse)
  .acceptJson()
  .get('https://api.example.local/users');

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

We encourage you to contribute to HTTP Client! Contributions are what makes the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

Please check out the contributing to HTTP Client guide for guidelines about how to proceed.

Security Vulnerabilities

Trying to report a possible security vulnerability in HTTP Client? Please check out our security policy for guidelines about how to proceed.

Sponsor

Do you like this project? Support it by donating.

License

The MIT License (MIT). Please see License File for more information.