2.2.0 • Published 1 year ago

@35up/http-client v2.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

http-client

Provides convenient apis to make http requests and handle the responses, eliminates boilerplate code. It is basically a wrapper over XHR requests (uses fetch).

APIs

The main API of the library is createMethod. This creates a ready to use function with some settings already embedded into it.

createMethod(method, baseUrl, defaultOptions)

Params:

ParameterDescriptionTypeRequired
methodHTTP method: GET, POST, PUT, etc.StringYes
baseUrlBase url of the request path (will be prefixed the final url). When not specified relative path will be used /StringNo
defaultOptionsRequest options that will be used by default. See details belowObjectNo

Options:

ParameterDescriptionTypeRequired
headersExtra headers you would like to passObjectNo
withCredentialsFlag whether to include cookies in the request (defaults to false)BooleanNo
modeRequest modeStringNo
paramsSearch params object. Will be trasnformed to query string and appended to the request urlObjectNo

createMethod returns a function with the following signature:

method(endpointUrl, body, options)

Parameters:

ParameterDescriptionTypeRequired
endpointUrlThe request endpoint. Will be appended to the baseUrlStringYes
bodyRequest bodyObjectNo
optionsRequest options. See details above. This will be merged with defaultOptions specified at createMethodObjectNo

Example

  import { createMethod } from '@35up/http-client';
  
  const put = createMethod(
    'PUT',
    'https://my-website/apis/v1',
    {
      withCredentials: true, 
      headers: {'Content-Type': 'application/octet-stream'},
    },
   );
   
  // And then just use it to make an http request
  const result = await put('/order', {sku: '12345'}, {mode: 'cors'});

The returned value is a promise with decoded response body.

In case response fails, method throws an exception of type HttpError

HttpError inherits from Error class and has the following extra properties:

PropertyDescriptionType
responseStatusStatus code (404, 500, etc.)Number
responseStatusTextStatus text (i.e. internal server error)String
dataReponse data. This may contain arbitrary objectObject

Checking if thrown exception is of type HttpError

This is possible with isHttpError utility:

  try {
    ...
    await method(...);
  } catch(e) {
    if (isHttpError(e)) {
      // ... An http error happened. handle it here
    }
    // Some other issue occured, deal with it in other way
  }

Shortcuts

The library also exposes ready to use methods that do not have a base url so you could bypass calling createMethod in case your api base url is the same as your website (using relative path):

  import { get } from '@35up/http-client';
  
  const result = await get('/api/v1/orders');

The available functions are: get, post, put, patch, deleteMethod, head;

Requirements

The library supports both browser and node environments.

Http-client depends on the Fetch API. If you support older browsers which may not yet provide these natively (e.g. IE), consider including a global polyfill in your bundled application, such as fetch.