3.1.0 • Published 4 years ago

fetch-me-json v3.1.0

Weekly downloads
1
License
ISC
Repository
github
Last release
4 years ago

fetch-me-json

High level API for fetch with sensible defaults making client server requests a breeze.

Installation

npm i fetch-me-json

Usage

Convention

import JSONFetch from 'fetch-me-json'

JSONFetch.<<method>>(<<endpoint>>, <<JSON-payload>>)
    .then(<<JSON-ResponseBody>> => ...)
    .catch(<<errorMessage>> => ...)

GET requests

import JSONFetch from 'fetch-me-json'
JSONFetch.get('/resources/1')
    .then(bodyInJSON => console.log(bodyInJSON))
    .catch(errorMessage => console.log(errorMessage))

You can also pass query parameters.

import JSONFetch from 'fetch-me-json'
JSONFetch.get('/resources/1', {
    optional_parameter: 1
})

POST, PUT, PATCH, DELETE

import JSONFetch from 'fetch-me-json'

JSONFetch.post('/resources', {
    id: 1,
    name: 'Tyler',
    type: 1,
})

JSONFetch.delete('/resources/1')

JSONFetch.put('/resources/1', {
    name: 'Durden',
    type: 1,
})

JSONFetch.patch('/resources/1', {
    type: 2,
})

Advanced

internal fetch

These are the internal fetch options that will be applied. You can configure these to your liking (see below).

{
    mode: 'same-origin',
    credentials: 'same-origin',
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
}

Configurations

import JSONFetch from 'fetch-me-json'

const configurations = {
    errorKey: 'error'
}

JSONFetch.config(configurations)

List of possible configurations

keydescriptiondefault
errorKeyThe key (from the response) that should be thrown in the case of an error. Pass null to throw entire responsemessage
defaultPayloaddefine default payload you always want to pass along
fetchparameters to be passed down to the global fetch method, overrides default parameterssee internal fetch above
baseURLURL to be prepended for every request's endpoint. E.g. /api or http://localhost:3000

Differences to native fetch

  • uses and accepts JSON by default
  • throws an error when response is not ok

If you need to support older browsers be sure to include the polyfill.

Catching the response status code

JSONFetch returns a custom HttpError object with a status property that you can make use of.

import JSONFetch from 'fetch-me-json'

JSONFetch.get('/resource').catch(error => {
    if (error instanceof JSONFetch.HttpError) {
        console.log(error.status)
    }
})
3.1.0

4 years ago

3.0.2

4 years ago

3.0.1

4 years ago

3.0.0

4 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago