1.0.1 • Published 5 years ago

@zakkudo/fetch v1.0.1

Weekly downloads
-
License
BSD-3-Clause
Repository
github
Last release
5 years ago

@zakkudo/fetch

Make using native fetch enjoyable.

Build Status Coverage Status Known Vulnerabilities Node License

Why use this?

  • Consistancy with simplicity
  • Automatically parses JSON payloads when the content type of the response is application/json
  • Automatically serializes json in the request body
  • Network errors throw an HttpError exception with the exception information for handling
  • Interpolates params into url templates. /users/:id/detail + {params: {id: "joe"}} = /users/joe/detail
  • Complex params are automatically JSON serialized similar to @zakkudo/query-string
  • Proper transformRequest/transformResponse/transformError hooks

Install

# Install using npm
npm install @zakkudo/fetch
# Install using yarn
yarn add @zakkudo/fetch

Examples

Post to an endpoint

import fetch from '@zakkudo/fetch';

//Create a user
fetch('http://example.com/users', {
    method: 'POST'
    body: {
        first_name: 'joe',
        last_name: 'johnson',
    },
}).then((reponse) => {
    console.log(response); // {'id': '1234'}
}.catch((reason) => {
    if (reason.status === 401) {
        return authenticate();
    }

    console.error(reason);
    throw reason;
});

Get data from an endpoint

import fetch from '@zakkudo/fetch';

//Fetch the created user
fetch('http://example.com/users/:id', {
    params: {
        id: '1234'
    },
}).then((reponse) => {
    console.log(response); // {id: '1234', first_name: 'joe', last_name: 'johnson'}
}.catch((reason) => {
    if (reason.status === 401) {
        return authenticate();
    }

    console.error(reason);
    throw reason;
});

Transform everything everywhere

import fetch from '@zakkudo/fetch';

//Fetch the created user
fetch('http://example.com/users/:id', {
    transformRequest(options) {
        return encodeWithJWT(options);
    },
    transformResponse(response) {
        const {first_name, last_name} = response;

        response.full_name = `${first_name} ${last_name}`;

        return response;
    },
    transformError(reason) {
        if (reason.status === 401) {
            window.href = '/login';
        }

        return reason;
    },
    params: {
        id: '1234'
    },
}).then((reponse) => {
    console.log(response); // {id: '1234', first_name: 'joe', last_name: 'johnson', full_name': 'joe johnson'}
});

Handling errors

import fetch from '@zakkudo/fetch';
import HttpError from '@zakkudo/fetch/HttpError';

fetch('http://example.com/does-not-exist').catch((reason) => {
    if (reason instanceof HttpError) {
        console.log(reason.status); // 404
    }
});

Use with async/await

import fetch from '@zakkudo/fetch';
import HttpError from '@zakkudo/fetch/HttpError';

async function get() {
    try {
        const response = await fetch('http://example.com/does-not-exist');
        console.log(response);
    } catch (e) {
        if (e instanceof HttpError) {
            console.log(e.status); // 404
        }
    }
}

API

@zakkudo/fetch~fetch(url, options) ⇒ Promise

Kind: Exported function

Returns: Promise - Resolves to the response of the network transaction or rejects with an HttpError
Throws:

  • HttpError For errors during the network transaction
  • UrlError For incorrectly formatted urls
  • QueryStringError On issues during serialization or construction of the query string
ParamTypeDescription
urlStringThe request url
optionsOptionsOptions modifying the network call, mostly analogous to fetch

fetch~Options : Object

Options modifying the network call, mostly analogous to fetch

Kind: inner typedef of fetch
Properties

NameTypeDefaultDescription
options.methodString'GET'GET, POST, PUT, DELETE, etc.
options.modeString'same-origin'no-cors, cors, same-origin
options.cacheString'default'default, no-cache, reload, force-cache, only-if-cached
options.credentialsString'omit'include, same-origin, omit
options.headersString"application/json; charset=utf-8".
options.redirectString'follow'manual, follow, error
options.referrerString'client'no-referrer, client
options.bodyString | ObjectJSON.stringify is automatically run for non-string types
options.paramsString | ObjectQuery params to be appended to the url. The url must not already have params. The serialization uses the same rules as used by @zakkudo/query-string
options.transformRequestfunction | Array.<function()>Transforms for the request body. When not supplied, it by default json serializes the contents if not a simple string. Also accepts promises as return values for asynchronous work.
options.unsafeBooleanDisable escaping of params in the url
options.transformResponsefunction | Array.<function()>Transform the response. Also accepts promises as return values for asynchronous work.
options.transformErrorfunction | Array.<function()>Transform the error response. Return the error to keep the error state. Return a non Error to recover from the error in the promise chain. A good place to place a login handler when recieving a 401 from a backend endpoint or redirect to another page. It's preferable to never throw an error here which will break the error transform chain in a non-graceful way. Also accepts promises as return values for asynchronous work.

@zakkudo/fetch/HttpError~HttpError ⇐ Error

An error representing an HTTP error during a network connection.

Kind: Exported class

Extends: Error

new HttpError(status, statusText, url, headers, response)

ParamTypeDescription
statusIntegerThe http error code
statusTextStringThe string representation of the error
urlStringThe url that failed
headersObjectThe headers when the request failed
response*The response of the transaction. Determined arbitraility by the server. Can be deserialized json.

httpError.status

The http error code

Kind: instance property of HttpError

httpError.statusText

The string representation of the error

Kind: instance property of HttpError

httpError.url

The url that failed

Kind: instance property of HttpError

httpError.headers

The headers when the request failed

Kind: instance property of HttpError

httpError.response

The response of the transaction. Determined arbitraility by the server. Can be deserialized json.

Kind: instance property of HttpError

@zakkudo/fetch/UrlError~UrlError ⏏

Aliased error from package @zakkudo/url/UrlError

Kind: Exported class

@zakkudo/fetch/QueryStringError~QueryStringError ⏏

Aliased error from package @zakkudo/url/QueryStringError

Kind: Exported class

1.0.1

5 years ago

1.0.0

5 years ago

0.0.14

6 years ago

0.0.13

6 years ago

0.0.12

6 years ago

0.0.11

6 years ago

0.0.10

6 years ago

0.0.9

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago