Skip to content

Repository files navigation

HttpClient

Typed wrapper around fetch or axios.

Github - ActionNPM PackageCode CoverageSonar Violations

This package's API is still developing and will not follow SEMVER until release 1.0.0.

HttpClient helps standardizes making HTTP calls regardless of the underlying client used, (fetch is used by default but other clients are available) and handling when errors are thrown. HttpClient works both in the browser and node environments. Exposes an interface to abort HTTP calls using AbortController. See below about using AbortController in older environments. Exposes an interface to control how requests and responses are handled. See below about using HttpClient's Request Strategies. Some strategies are provided in this package, but you can also implement your own strategies. List of strategies are provided below.

Installation

npm install @seriouslag/httpclient

Example

To see additional examples look in the `src/examples/` directory.

Basic example:

import{HttpClient}from'@seriouslag/httpclient';interfaceNamedLink{name: string;url: string;}interfacePokemonPage{count: number;next: string|null;previous: string|null;results: NamedLink[];}consthttpClient=newHttpClient();asyncfunctionfetchPokemonPage(offset: number=0,pageSize: number=20){constpokemonApiUrl='https://pokeapi.co/api/v2';returnawaitthis.httpClient.get<PokemonPage>(`${pokemonApiUrl}/pokemon`,{params: {offset: offset,limit: pageSize,},});}// IIFE(async()=>{constresults=awaitfetchPokemonPage(0,100);console.log(results);})();

Using axios

We can use axios as the underlying client by installing the @seriouslag/httpclient-axios package. A custom client adaptor can be provided to the HttpClient constructor, an interface is exposed to allow for custom client adaptors to be created.

npm install @seriouslag/httpclient @seriouslag/httpclient-axios

Axios can be configured, axios options can be passed into the constructor of HttpClient.

import{HttpClient}from'@seriouslag/httpclient';import{AxiosClientAdaptor}from'@seriouslag/httpclient-axios';import{Agent}from'https';consthttpsAgent=newAgent({rejectUnauthorized: false,});constaxiosClientAdaptor=newAxiosClientAdaptor({
httpsAgent,});consthttpClient=newHttpClient(axiosClientAdaptor);

Using AbortController

Each of the HTTP methods of the HttpClient accept an instance of a AbortController. This allows HTTP requests to be cancelled if not already resolved.

import{HttpClient}from'@seriouslag/httpclient';interfacePokemonPage{count: number;next: string|null;previous: string|null;results: NamedLink[];}constpokemonApiUrl='https://pokeapi.co/api/v2';consthttpClient=newHttpClient();constcancelToken=newAbortController();constrequest=httpClient.get<PokemonPage>(`${pokemonApiUrl}/pokemon`,cancelToken,);cancelToken.abort();try{constresult=awaitrequest;console.log('Expect to not get here because request was aborted.',result);}catch(e){console.log('Expect to reach here because request was aborted.');}

AbortController in older environments

Abort controller is native to node 15+ and modern browsers. If support is needed for older browsers/node versions then polyfills can be found. This polyfill is used in the Jest test environment for this repository: abortcontroller-polyfill

import'abortcontroller-polyfill/dist/abortcontroller-polyfill-only';import{HttpClient}from'@seriouslag/httpclient';consthttpClient=newHttpClient();

Using Request Strategies

A request strategy is middleware to handle how requests are made and how responses are handled. This is exposed to the consumer using the `HttpRequestStrategy` interface. A request strategy can be passed into the HttpClient (it will be defaulted if not) or it can be passed into each request (if not provided then the strategy provided by the HttpClient will be used). A custom strategy can be provided to the HttpClient's constructor.

Provided strategies:

  • DefaultHttpRequestStrategy - Throws when a response's status is not 2XX
  • ExponentialBackoffRequestStrategy - Retries requests with a backoff. Throws when a response's status is not 2XX
  • MaxRetryHttpRequestStrategy - Retries requests. Throws when a response's status is not 2XX
  • TimeoutHttpRequestStrategy - Requests have are canceled if a request takes longer then provided timeout. Throws when a response's status is not 2XX

Using Request Strategy in the constructor

The following code creates an instance of the HttpClient with a custom HttpRequestStrategy, all requests will now use this strategy by default.

import{HttpClient,HttpRequestStrategy}from'@seriouslag/httpclient';classCreatedHttpRequestStrategyimplementsHttpRequestStrategy{/** Passthrough request to axios and check response is created status */publicasyncrequest<T=unknown>(client: AxiosInstance,axiosConfig: AxiosRequestConfig){constresponse=awaitclient.request<T>(axiosConfig);this.checkResponseStatus<T>(response);returnresponse;}/** Validates the HTTP response is successful created status or throws an error */privatecheckResponseStatus<T=unknown>(response: HttpResponse<T>): HttpResponse<T>{constisCreatedResponse=response.status===201;if(isCreatedResponse){returnresponse;}throwresponse;}}consthttpRequestStrategy=newCreatedHttpRequestStrategy();// all requests will now throw unless they return an HTTP response with a status of 201consthttpClient=newHttpClient({
httpRequestStrategy,});

Using Request Strategy in a request

The following code creates an instance of the HttpClient with a provided HttpRequestStrategy (MaxRetryHttpRequestStrategy), then starts a request and passes a different strategy (DefaultHttpRequestStrategy) to the request. The request will now used the strategy provided instead of the HttpClients strategy.

import{HttpClient,DefaultHttpRequestStrategy,MaxRetryHttpRequestStrategy}from'@seriouslag/httpclient';consthttpClient=newHttpClient({httpRequestStrategy: newMaxRetryHttpRequestStrategy(10),});// IIFE(async()=>{constresponse=awaithttpClient.get('/endpoint',{httpRequestStrategy: newDefaultHttpRequestStrategy(),});})();

Logging

An interface is exposed to the HttpClient constructor to allow a logging instance to be provided.

constlogger: Logger={info: (message: string, ...args: unknown[])=>console.log(message, ...args),warn: (message: string, ...args: unknown[])=>console.warn(message, ...args),error: (message: string, ...args: unknown[])=>console.error(message, ...args),debug: (message: string, ...args: unknown[])=>console.debug(message, ...args),};consthttpClient=newHttpClient({
logger,});

Contributing

Contributing

About

Typed opinionated library to make HTTP calls in node and the browser.

Topics

Resources

Contributing

Stars

12 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages