1.0.9 • Published 5 years ago

@jellyfish-commuting/fetchjson v1.0.9

Weekly downloads
15
License
MIT
Repository
github
Last release
5 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 params
  • optional method prefix

Install

yarn add @jellyfish-commuting/fetchjson

or

npm install @jellyfish-commuting/fetchjson

Usage

import fetchjson from '@jellyfish-commuting/fetchjson';

// Init params
const init = {
 hostname: 'https://fake-api.io',
 authorization: 'Bearer API_KEY',
};

// Fetch (https://fake-api.io/v1/users?limit=10)
fetchjson('v1/users', { limit: 10 }, init)
  .then(payload => console.log(payload));

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

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

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

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

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

(1) init argument can be extends with following optional properties

PropTypeNote
hostnamestringPrepend URL with hostname if url don't start by a domain
authorizationstringAuthorization header Ignored if url don't start by hostname property
const init = {
 hostname: 'https://fake-api.io',
 authorization: 'Bearer API_KEY',
};

// Endpoint will be prepend with hostname
fetchjson('POST v1/users', { firstname: 'John' }, init);

// Authorization will be ignored 
// -> hostname is different than init.hostname
fetchjson('https://vendor-api.io/v1/my-account', init);

Return value

Promise resolve with json payload

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

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

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago