2.5.4 • Published 3 years ago

funtch v2.5.4

Weekly downloads
394
License
MIT
Repository
github
Last release
3 years ago

funtch - Functional Fetch

CI Status Doc Status codecov npm version Quality Gate Status

Fetch based on isomorphic-fetch with functional and customizable behavior.

Getting started

Add dependency to your project

npm i -S funtch

Usage

Full documentation is available here.

Full usage example in example folder

ES6

import funtch from 'funtch';

funtch.get('https://api.github.com').then((data) => doSomething(data));

CommonJS

const funtch = require('funtch').default;

funtch.get('https://api.github.com').then((data) => doSomething(data));

API

You can send HTTP requests from common verbs by invoking the following methods from funtch:

Methode nameParamsDescription
geturl: String query: Object/MapPerform a GET with optional query params
posturl: String body: AnyPerform a POST with given body and Content-type guessed from param
puturl: String body: AnyPerform a PUT with given body and Content-type guessed from param
patchurl: String body: AnyPerform a PATCH with given body and Content-type guessed from param
deleteurl: StringPerform a DELETE

If default pattern doesn't match your needs, you can build a step by step request by invoking funtch.url(url: String) and applying following methods:

Method nameParamsDescription
queryquery: Object/MapAppend query params when requesting
headerkey: String value: StringAdd HTTP header
authvalue: StringAdd Authorization Header with given value
contentJsonAdd Content-type: application/json header
contentTextAdd Content-type: text/plain header
guessContentTypebody: AnyGuess content type by checking if body is a JSON. If true, content is set to JSON, otherwise to text
acceptJsonAdd Accept: application/json header
acceptTextAdd Accept: text/plain header
contentHandlercallback: func(response)See content handler
errorHandlercallback: func(response, contentHandler)See error handler
abortHandlercallback: func(error)Callback method when request is aborted
fullResponseReturn complete response with {status, headers, data}, instead of just raw data by default
bodybody: Any guess: Boolean default trueSet body content of request, and guessing content on the fly
getSet method to GET and send request
postbody: AnySet method to POST, add body if provided with content guess and send request
putbody: AnySet method to PUT, add body if provided with content guess and send request
patchbody: AnySet method to PATCH, add body if provided with content guess and send request
deleteSet method to DELETE and send request
methodmethod: StringSet HTTP method to given value
sendSend request as it
abortAbort request

All these methods, except abort, are chainable and once send is called, the result is a Promise.

const fetchPromise = funtch
  .url('https://api.github.com')
  .auth('Basic SECRET')
  .contentJson()
  .acceptJson()
  .post({ star: true });

fetchPromise
  .then((data) => console.log(data))
  .catch((err) => console.error(data));

Cancelable request can be done this way.

const fetchRequest = funtch
  .url('https://api.vibioh.fr/delay/10') // 10 seconds delay
  .abortHandler((e) => console.warn(`Request was aborted: ${e.name}`));

fetchRequest.get();
fetchRequest.abort();

You can create a pre-configured builder, in order to avoid repeating yourself, by passing an object to the withDefault method with keys as the config function name.

const funtcher = funtch.withDefault({
  baseURL: 'https://api.github.com',
  auth: 'github SecretToken',
  fullResponse: true,
  contentJson: true,
});

funtcher.get('/user/keys').then((response) => doSomething(response.data));
funtcher
  .post('/user/keys', 'my-ssh-key')
  .then((response) => doSomething(response.data));

Error Handling

By default, funtch will rejects promise with a full response describing error if HTTP status is greater or equal than 400. This object contains HTTP status, response headers and data (in plain text or JSON, according to content handler).

{
  status: 404,
  headers: {
    'content-length': '19',
    'content-type': 'text/plain; charset=utf-8',
    date: 'Sat, 06 May 2017 11:58:38 GMT',
    'x-content-type-options': 'nosniff',
    connection: 'close'
  },
  data: '404 page not found',
}

Customization

Custom content handler

By default, fetch exposes only two methods for reading content : text() and json(). Instead of juggling with these methods, funtch return content by examining Content-Type header and call one of the two methods.

You can easily override default content handler by calling content() on the build. The content handler method accepts a reponse and return a Promise. Method is also passed to error handler method, in order to read content while identifying error.

Below an example that parse XML response.

import funtch { MEDIA_TYPE_JSON, CONTENT_TYPE_HEADER } from 'funtch';

const contentTypeJsonRegex = new RegExp(MEDIA_TYPE_JSON, 'i');
const contentTypeXmlRegex = /application\/xml/i;

function xmlContent(response) {
  if (contentTypeJsonRegex.test(response.headers.get(CONTENT_TYPE_HEADER))) {
    return response.json();
  }

  return new Promise(resolve => {
    response.text().then(data => {
      if (contentTypeXmlRegex.test(response.headers.get(CONTENT_TYPE_HEADER))) {
        resolve(new DOMParser().parseFromString(data, 'text/xml'));
      }
      resolve(data);
    });
  });
}

funtch
  .url('https://api.github.com')
  .content(xmlContent)
  .get();

Custom error handler

By default, fetch returns a valid Promise without considering http status. Funtch error handler is called first, in this way, you can identify an error response and reject the Promise. By default, if HTTP status is greather or equal than 400, it's considered as error.

You can easyly override default error handler by calling errorHandler() on the builder. The error handler method accepts a response and a content handler, and return a Promise. You can reimplement it completely or adding behavior of the default one.

Below an example that add a toString() behavior.

import funtch, { errorHandler } from 'funtch';

function errorWithToString(response) {
  return new Promise((resolve, reject) =>
    errorHandler(response)
      .then(resolve)
      .catch((err) =>
        reject({
          ...err,
          toString: () => {
            if (typeof err.content === 'string') {
              return err.content;
            }
            return JSON.stringify(err.content);
          },
        }),
      ),
  );
}

funtch
  .url('https://api.github.com')
  .errorHandler(errorWithToString)
  .get()
  .catch((err) => console.log(String(err)));
2.5.4

3 years ago

2.5.2

3 years ago

2.5.3

3 years ago

2.5.1

3 years ago

2.5.0

3 years ago

2.4.3

3 years ago

2.4.2

3 years ago

2.4.1

3 years ago

2.4.0

3 years ago

2.3.0

3 years ago

2.2.2

3 years ago

2.2.1

4 years ago

2.2.0

4 years ago

2.1.1

4 years ago

2.1.0

4 years ago

2.0.10

5 years ago

2.0.9

5 years ago

2.0.8

5 years ago

2.0.7

5 years ago

2.0.6

5 years ago

2.0.5

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.6.0

5 years ago

1.5.22

5 years ago

1.5.21

5 years ago

1.5.20

5 years ago

1.5.19

5 years ago

1.5.18

5 years ago

1.5.17

5 years ago

1.5.16

5 years ago

1.5.15

5 years ago

1.5.14

5 years ago

1.5.13

5 years ago

1.5.12

5 years ago

1.5.11

5 years ago

1.5.10

5 years ago

1.5.9

5 years ago

1.5.7

6 years ago

1.5.6

6 years ago

1.5.5

6 years ago

1.5.4

6 years ago

1.5.2

6 years ago

1.5.1

6 years ago

1.4.3

6 years ago

1.4.2

6 years ago

1.4.1

6 years ago

1.4.0

6 years ago

1.3.0

7 years ago

1.2.1

7 years ago

1.2.0

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.0.1

7 years ago