2.0.3 • Published 3 years ago

@jollie/fetchjson v2.0.3

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

Version Licence Build Coverage Downloads

for internal use only - Just draft idea to easily fetch API in our apps

fetchjson

Fetch wrapper to easily request an API, simply create a native fetch initialized with :

  • header Content-Type=application/json
  • default hostname & authorization credentials
  • optional method prefix

Install

yarn add @jollie/fetchjson

or

npm install @jollie/fetchjson

Usage

import makeFetch from '@jollie/fetchjson';

// Create fetchjson to consume your API
const fetchjson = makeFetch('api.vendor-domain.io', 'API_KEY');

// Create
fetchjson('POST v1/users', { firstname: 'John', lastname: 'Doe' })
  .then(({ id )} => console.log(`User #${id} created successfully !`));

// Update
fetchjson('PUT v1/users/1', { firstname: 'Johnna' })
  .then(() => console.log('User updated successfully !'));

// Delete
fetchjson('DELETE v1/users/1')
  .then(() => console.log('User deleted successfully !'));

// Retrieve http response 
// payload has a not enumerable prop "_response"
fetchjson('v1/users')
  .then(payload => {
    const header = payload._response.headers.get('x-powered-by');
    console.log(`Powered by ${header || 'Unknow'}`),
  });

Params

const fetchjson = makeFetch(domain, api_key);
PropTypeNote
domainstringdomain of your api
api_keystringToken for Authorization header Bearer {api_key}

makeFetch return function with following params

fetchjson(url, data, init);
PropTypeNote
urlstringURL to fetch Could be prefixed by a http method fetchjson('POST https://fake-api.io/v1/users')
dataobjectqueryString or Body param according http method
init1objectInit arg passed to native fetch - see fetch

Return value

Promise resolve with json payload