ackee-http-client v2.2.5
IMPORTANT
ackee-http-clientwas renamed to@ackee/antonio. The repository is available on Github.
ackee-http-client
The HTTP client uses axios for making all HTTP requests and ackee-redux-token-auth for setting a access token to HTTP Authorization header.
Table of contents
Installing
Using yarn:
$ yarn add ackee-http-clientUsing npm:
$ npm install ackee-http-clientInitialization
Initialization is a simple 2 steps process.
By creating a new instance of HttpClient, you will get api, authApi objects and saga function. Then you connect the saga among your other sagas. That's all.
1. Create httpClient instance
Create one httpClient instance object per project.
import { create } from 'ackee-http-client';
const { api, authApi, saga } = create({
baseURL: 'https://base-url.com/api/',
});
export { api, authApi, saga };2. Launch HttpClient saga
import { saga as httpClient } from 'Config/http-client';
export default function*() {
// httpClient saga must come before redux-token-auth saga
yield all([httpClient()]);
}Usage
api - unauthorized requests
See available properties of the api object.
import { api } from 'Config/http-client';
async function fetchTodo(todoId) {
const response = await api.get(`/todos/${todoId}`, {
// overwrite the default baseURL
baseURL: 'https://jsonplaceholder.typicode.com/',
});
return response.data;
}authApi - authorized requests
By using methods under authApi object, it's guaranteed that each HTTP request is going to have access token in its Authorization header.
If the access token isn't available at the moment, the request is paused by take(ACCESS_TOKEN_AVAILABLE) effect, and timeout, if enabled, is set. See accessTokenUnavailableTimeout at create method for more details.
See available properties of the authApi object.
import { authApi } from 'Config/http-client';
async function fetchPost(postId) {
const response = await authApi.get(`/posts/${postId}`);
return response.data;
}Shared
defaultsEven though
apiandauthApiare created as separated axios instances, they share the same default request config object -api.defaultsandauthApi.defaults. This issue/feature is caused by how axios is implemented andackee-http-clientwon't change it. Just don't be surprised, when you see theAuthorizationheader also in requests created by theapi.
API
create(axiosRequestConfig: Object, customConfig: Object) => httpClient:Object
This method receives two objects as arguments.
axiosRequestConfig: ObjectThe
axiosRequestConfigis reserved for axios default request configuration, see available options.customConfig: ObjectThe
customConfigobject offers following default options:{ // If `manageAuthHeader` is true, then when access token state changes, // the `setAuthHeader` is triggered. // If it's false, `setAuthHeader` won't be ever triggered. manageAuthHeader: true, /** * If `manageAuthHeader` is enabled, `setAuthHeader` receives * object with default headers, when access token state changes. * @param {Object} headers - reference to axios default request headers object (https://github.com/axios/axios#custom-instance-defaults) * @param {String|null} accessToken */ setAuthHeader(headers, accessToken) { if (accessToken) { // `common` indicates that it's a default header for all HTTP methods headers.common.Authorization = `Bearer ${accessToken}`; } else { delete headers.common.Authorization; } }, // If it's used `authApi` and access token isn't available, // there is optionable timeout with following default values: accessTokenUnavailableTimeout: { // enable / disable the timeout enabled: false, // set timeout duration for 30s duration: 1000 * 30, // if silent is true, then throw a custom error, // othewise API request will be made that fails, // and throws a server error silent: false, }, }
And returns:
httpClient: Objectapi,authApiThe
httpClientobject contains two axios instances:apiandauthApiwith the same properties:api.request(config)api.get(url[, config])api.delete(url[, config])api.head(url[, config])api.options(url[, config])api.post(url[, data[, config]])api.put(url[, data[, config]])api.patch(url[, data[, config]])api.getUri([config])api.defaultsapi.interceptors
configuriParams: Object- Key-value object containing request uri params. Params that are found in url are replaced, rest is ignored.yield api.get('/todos/:todoId', { baseURL: 'https://jsonplaceholder.typicode.com', uriParams: { // ':todoId' will be replaced with '1' todoId: '1', // 'foo' will be ignored and won't be added as a query parameter foo: '2, }, });See rest of available options - axios/request-config
#### `saga`
Internal saga primarily for communication with `ackee-redux-token-auth`.Example
import { create } from 'ackee-http-client';
const { authApi } = create(
{
baseURL: 'https://jsonplaceholder.typicode.com/',
},
{
// Customize setting of the authorization header
// by providing a custom setAuthHeader method:
setAuthHeader(headers, accessToken) {
if (accessToken) {
headers.common.Authorization = accessToken;
} else {
delete headers.common.Authorization;
}
},
},
);
async function fetchTodo() {
const response = await authApi.get('/todos/1');
return response.data;
}Saga Effects
Custom Saga effects with built-in cancelation of API requests, see the docs.