npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ackee/antonio

v3.0.6

Published

A HTTP client built on axios. An access token is injected to authorization header by @ackee/petrus.

Downloads

68

Readme

ackee|Antonio

GitHub license CI Status PRs Welcome Dependency Status bundlephobia bundlephobia

Antonio

A HTTP client that uses axios for making all HTTP requests and @ackee/petrus for adding an access token to the Authorization header.

Table of contents


Installing

Using yarn:

$ yarn add @ackee/antonio

Using npm:

$ npm i -S @ackee/antonio

Initialization

1. Create new instance

import * as Antonio from '@ackee/antonio';

const defaultRequestConfig = {
    baseURL: 'https://base-url.com/api',
};

const { api, authApi, saga } = Antonio.create(defaultRequestConfig);

export { api, authApi, saga };

2. Connect the saga

Initializes the saga handlers generator. This should be passed along with your other sagas.

import { saga as antonio } from 'Config/antonio';

export default function* () {
    // antonio's saga must come before @ackee/petrus saga
    yield all([antonio()]);
}

Usage

api - unauthorized requests

See available properties of the api object.

import { api } from 'Config/antonio';

function* fetchTodo(todoId) {
    const response = yield api.get('/todos/:todoId', {
        // overwrite the default baseURL
        baseURL: 'https://jsonplaceholder.typicode.com/',
        uriParams: {
            todoId,
        },
    });

    return response.data;
}

authApi - authorized requests

By using methods under authApi object, it's guaranteed that each HTTP request is going to have an 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 the accessTokenUnavailableTimeout for more details.

See available properties of the authApi object.

import { authApi } from 'Config/antonio';

function* fetchPost(postId) {
    const response = yield authApi.get(`/posts/${postId}`);

    return response.data;
}

Shared defaults

Even though api and authApi are created as separated axios instances, they share the same default request config object - api.defaults and authApi.defaults. This issue/feature is caused by how axios is implemented and @ackee/antonio won't change it. Just don't be surprised, when you see the Authorization header also in requests created by the api.


API

create(defaultRequestConfig: Object, customConfig: Object) => Object

This method receives two objects as arguments.

  • defaultRequestConfig: Object

    The defaultRequestConfig object is passed to axios as default request configuration.

    Available properties:

    • axios request config
    • additional props:
      // `uriParams` - Key-value object containing request uri params. Params that are found in url are replaced, rest is ignored.
      uriParams: {
          // ':todoId' will be replaced with '1'
          // '/todos/:todoId' -> '/todos/1'
          todoId: '1',
      },
  • customConfig: Object

    The customConfig object 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 {Object|null} accessToken
         */
        setAuthHeader(headers, accessToken) {
            if (accessToken) {
                // `common` indicates that it's a default header for all HTTP methods
                headers.common.Authorization = `Bearer ${accessToken.token}`;
            } 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:

  • Object

    api, authApi

    api and authApi have the same following 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.defaults
    • api.interceptors

    saga

    Internal saga, primarily for communication with @ackee/petrus.

Example

import * as Antonio from '@ackee/antonio';

const { authApi } = Antonio.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.tokenType} ${accessToken.token}`;
            } 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.

Utilities

setAuthHeader(headers: CommonHeaders, accessToken: string | null): void

A utility used in the default config for setting bearer access token value to Authorization header.