f3tch
v4.0.10
Published
Interface around javascript's fetch Api
Downloads
11
Maintainers
Readme
f3tch
A wrapper around javascript's fetch Api with customizable profiles, built with async / await.
The main purpose is to create profiles that one can reuse for DRY code.
Table of content
- Installation
- Examples _ Basic usage _ Full Example * Real World Example
- f3tch documentation
- profile documentation
- LICENSE
Installation
npm install --save f3tch
or if using yarn
yarn add f3tch
Examples
Basic usage
import f3tch from `f3tch`
async function makeRequest() {
try {
const response = await f3tch('https://your.url.com').get()
const json = await response.json()
// Do something
} catch(error) {
// Do something
}
}
Full example
import f3tch, {profile} from `f3tch`
const myProfile = profile('http://your.endpoint.com')
.headers(() => {
// Get the latest token from session / local storage
// Or from anywhere else
return {
Authorization: 'JWT someToken'
}
})
.responder(async (response) => {
const json = await response.json()
return json
})
async function makeApiCall() {
try {
const reseponse = await f3tch('/api/endoint')
.profile(myProfile)
.headers({
Accept: 'application/json'
})
.query({
foo: 'foo',
bar: true,
})
.query('q=1')
.query({
arr: [1, 2, 3],
indexArray: {
value: ['a', 'v'],
format: 'index',
separator: '!=',
},
brackets: {
value: ['x', 'z'],
format: 'brackets',
},
obj: {
value: 'wawa',
separator: '!='
}
})
.get()
// Do something with the response
} catch(error) {
// Do something with the error
}
}
Real world example
// myProfile.js
import {profile} from 'f3tch';
export default profile('http://api.endpoint.com')
.headers(() => ({
Authorization: `JWT ${localStorage.get('token')}`,
Accept: 'application/json',
}))
.bodyParser((data) => JSON.stringify(data))
.responder(async (response) => await response.json());
// users.api.js
// Import myProfile
import profile from './path/to/myProfile.js';
import f3tch from 'f3tch';
export const getUsers = (query = {}) =>
f3tch('/users/').profile(profile).query(query).get();
export const getUserById = (id) =>
f3tch(`/users/${id}/`).profile(profile).get();
export const createUser = (user = {}) =>
f3tch('/users/').profile(profile).body(data).post();
export const updateUser = (user = {}) =>
f3tch('/users/').profile(profile).body(data).put();
export const deleteUser = (id) =>
f3tch(`/users/${id}/`).profile(profile).delete();
// App.js
// Using created endpoint functions somewhere in the application
import {
getUsers,
getUserById,
createUser,
updateUser,
deleteUser,
} from './path/to/users.api.js';
const getUsersApi = async () => {
try {
const users = await getUsers();
// Do something
} catch (error) {
// Do something with the error
}
};
const getUserByIdApi = async (id) => {
try {
const user = await getUserById(id);
// Do something
} catch (error) {
// Do something with the error
}
};
const createUserApi = async (user) => {
try {
const user = await createUser(user);
// Do something
} catch (error) {
// Do something with the error
}
};
const updateUserApi = async (user) => {
try {
const user = await updateUser(user);
// Do something
} catch (error) {
// Do something with the error
}
};
const deleteUserApi = async (id) => {
try {
await deleteUser(id);
// Do something
} catch (error) {
// Do something with the error
}
};
f3tch documentation
f3tch
f3tch(String | Function);
Parameters:
- url [String | Function] :: Request's endpoint. Can be a string or a function that returns a string.
Returns:
- F3tch instance
Examples:
f3tch('https://your.url.com');
f3tch(() => 'https://your.url.com');
f3tch .profile
.profile(Object)
Parameters:
- profile [Object] :: Profile object
Returns:
- F3tch instance
Example:
import profile from './profile.js';
f3tch(url).profile(profile);
f3tch .mode
.mode(String)
Parameters:
- mode [String] :: fetch's mode option. Can be one of:
same-origin, cors, cors-with-forced-preflight, no-cors
.
Returns:
- F3tch instance
Example:
f3tch(url).mode('same-origin');
f3tch .credentials
.credentials(String)
Parameters:
- credentials [String] :: fetch's credentials option. Can be one of:
omit, same-origin, include
.
Returns:
- F3tch instance
Example:
f3tch(url).credentials('omit');
f3tch .headers
.headers(Object | Function)
Parameters:
- headers [Object | Function] :: Request headers. Can be an object or a function that returns an object.
Returns:
- F3tch instance
Examples:
The .headers()
function is stackable so it can be called multiple times.
f3tch(url).headers({
Accept: 'application/json',
Authorization: 'JWT token',
});
const getHeaders = () => ({
Accept: 'application/json',
Authorization: 'JWT token',
});
f3tch(url).headers(getHeaders);
f3tch(url)
.headers({
Accept: 'application/json',
})
.headers({
Authorization: 'JWT token',
});
f3tch .query
.query(String | Object | Function)
Parameters:
- query [String | Object | Function] :: Request query. Can be a string (
key=value
), an object ({key: 'value'}
) or a function that returns either a string or an object.
Returns:
- F3tch instance
Examples:
The .query()
function is stackable so you can call it multiple times.
There are multiple ways and options to create a query. The simplest way is to pass in a string that would go directly into to the url:
f3tch(url).query('key=value');
The second option is to pass in a simple object with key value pairs like {key: 'value'}
that would be converted into key=value
. If the value is a boolean
({key: true}
) it will be converted into a string like key=true
and if it's an array
({key: ['a', 1, true]}
) it will be converted into key=a&key=1&key=true
.
If working with the query object there are some options to build out the query. The default separator between the key and value is =
but it can be changed like this:
{
foo: {
value: 'bar',
separator: '!='
}
}
// This would convert to
// foo!=bar
Similar options apply for working with array
values but there is one more option to determinate if there should be brackets in the key or not and if the brackets should take the index into account. The parameter is called format
and can be one of: null, index or brackets
:
{
foo: {
value: ['a', 'b'],
separator: '!='
},
bar: {
value: ['a', 'b'],
format: 'index'
},
baz: {
value: ['a', 'b'],
format: 'brackets'
}
}
// This would convert to
// foo=a&foo=b&bar[1]=a&bar[2]=b&baz[]=a&baz[]=b
And here is an example using all possibilities:
f3tch(url)
.query({
foo: 'foo',
bar: true,
})
.query('q=1')
.query({
arr: [1, 2, 3],
indexArray: {
value: ['a', 'v'],
format: 'index',
separator: '!=',
},
brackets: {
value: ['x', 'z'],
format: 'brackets',
},
obj: {
value: 'wawa',
separator: '!=',
},
});
f3tch .retry
.retry(Number | Function)
Parameters:
- retry [Number | Function] (Default: 0) :: Number of retries after if api call fails. If a function is used it needs to return a number.
Returns:
- F3tch instance
Example:
f3tch(url).retry(3);
f3tch .retryTimeout
.retryTimeout(Number | Function)
Parameters:
- retryTimeout [Number | Function] (Default: 500) :: How soon after failure the API call should be called again (ms). If a function is used it needs to return a number.
Returns:
- F3tch instance
Example:
f3tch(url).retryTimeout(300);
f3tch .body
.body(Any | Function)
Parameters:
- body [Any | Function] :: Request body. Can be any value. It is the developers responsibility to pass in the values needed. It can also be a function that returns the needed value.
Returns:
- F3tch instance
Example:
const body = JSON.stringify({
key: 'value',
});
f3tch(url).body(body);
f3tch .bodyParser
.bodyParser(Function)
Parameters:
- bodyParser [Function] :: Function that modified data passed into the
.body
function
Returns:
- F3tch instance
Example:
const body = {
key: 'value',
};
f3tch(url)
.body(body)
.bodyParser((data) => JSON.stringify(data));
f3tch .preRequest
.preRequest(Function)
Parameters:
- preRequest [Function] :: Function that gets called right before the API call is being made
Returns:
- F3tch instance
Example:
const somethingDoesNotAddUp = true;
f3tch(url)
.body(body)
.preRequest(() => {
if (somethingDoesNotAddUp) throw new Error('Did not add up');
});
f3tch .get
.get()
Description:
Creating a GET
HTTP request.
Returns:
- Promise
Example:
// async / await
async function makeRequest() {
try {
const response = await f3tch(url).get();
return response;
} catch (error) {
throw error;
}
}
// Promise
f3tch(url)
.get()
.then((response) => {
// Do something with the response
})
.catch((error) => {
// Do something with the error
});
f3tch .post
.post()
Description:
Creating a POST
HTTP request.
Returns:
- Promise
Example:
// async / await
async function makeRequest() {
try {
const response = await f3tch(url).post();
return response;
} catch (error) {
throw error;
}
}
// Promise
f3tch(url)
.post()
.then((response) => {
// Do something with the response
})
.catch((error) => {
// Do something with the error
});
f3tch .patch
.patch()
Description:
Creating a PATCH
HTTP request.
Returns:
- Promise
Example:
// async / await
async function makeRequest() {
try {
const response = await f3tch(url).patch();
return response;
} catch (error) {
throw error;
}
}
// Promise
f3tch(url)
.patch()
.then((response) => {
// Do something with the response
})
.catch((error) => {
// Do something with the error
});
f3tch .put
.put()
Description:
Creating a PUT
HTTP request.
Returns:
- Promise
Example:
// async / await
async function makeRequest() {
try {
const response = await f3tch(url).put();
return response;
} catch (error) {
throw error;
}
}
// Promise
f3tch(url)
.put()
.then((response) => {
// Do something with the response
})
.catch((error) => {
// Do something with the error
});
f3tch .delete
.delete()
Description:
Creating a DELETE
HTTP request.
Returns:
- Promise
Example:
// async / await
async function makeRequest() {
try {
const response = await f3tch(url).delete();
return response;
} catch (error) {
throw error;
}
}
// Promise
f3tch(url)
.delete()
.then((response) => {
// Do something with the response
})
.catch((error) => {
// Do something with the error
});
f3tch .head
.head()
Description:
Creating a HEAD
HTTP request.
Returns:
- Promise
Example:
// async / await
async function makeRequest() {
try {
const response = await f3tch(url).head();
return response;
} catch (error) {
throw error;
}
}
// Promise
f3tch(url)
.head()
.then((response) => {
// Do something with the response
})
.catch((error) => {
// Do something with the error
});
f3tch .options
.options()
Description:
Creating a OPTIONS
HTTP request.
Returns:
- Promise
Example:
// async / await
async function makeRequest() {
try {
const response = await f3tch(url).options();
return response;
} catch (error) {
throw error;
}
}
// Promise
f3tch(url)
.options()
.then((response) => {
// Do something with the response
})
.catch((error) => {
// Do something with the error
});
profile documentation
profile
profile(String);
Parameters:
- url [String] :: Base url
Returns:
- Profile instance
Examples:
profile('https://your.url.com');
profile .url
.url(String | Function)
Parameters:
- url [String | Function] :: Request's base endpoint. Can be a string or a function that returns a string.
Returns:
- Profile instance
Examples:
profile().url('https://your.url.com');
profile().url(() => 'https://your.url.com');
profile .responder
.responder(Function)
Parameters:
- responderFunction [Function] :: Function that handles the response.
Returns:
- Profile instance
Examples:
// async / await
async function convertToJson(response) {
const json = await response.json();
return json;
}
profile().responder(convertToJson);
// Promise
function convertToJson(response) {
return response
.json()
.then((json) => json)
.catch((error) => error);
}
profile().responder(convertToJson);
profile .mode
.mode(String)
Check out .mode. It is the same API only for a profile.
profile .credentials
.credentials(String)
Check out .credentials. It is the same API only for a profile.
profile .headers
.headers(Object | Function)
Check out .headers. It is the same API only for a profile.
profile .query
.query(String | Object | Function)
Check out .query. It is the same API only for a profile.
profile .retry
.retry(Number | Function)
Check out .retry. It is the same API only for a profile.
profile .retryTimeout
.retryTimeout(Number | Function)
Check out .retryTimeout. It is the same API only for a profile.
profile .body
.body(Any | Function)
Check out .body. It is the same API only for a profile.
profile .bodyParser
.bodyParser(Function)
Check out .bodyParser. It is the same API only for a profile.
profile .preRequest
.preRequest(Function)
Check out .preRequest. It is the same API only for a profile.
LICENSE
MIT License
Copyright (c) 2017 Matt Hahn
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.