1.0.9 • Published 5 years ago
@jellyfish-commuting/fetchjson v1.0.9
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);
Prop | Type | Note |
---|---|---|
url | string | URL to fetch Could be prefixed by a http method fetchjson('POST https://fake-api.io/v1/users') |
data | object | queryString or Body param according http method |
init 1 | object | Init arg passed to native fetch - see fetch |
(1) init
argument can be extends with following optional properties
Prop | Type | Note |
---|---|---|
hostname | string | Prepend URL with hostname if url don't start by a domain |
authorization | string | Authorization 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