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);
Prop | Type | Note |
---|---|---|
domain |
string |
domain of your api |
api_key |
string |
Token for Authorization header Bearer {api_key}
|
makeFetch return function with following 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 |
Return value
Promise resolve with json payload