@ackee/antonio 中文文档教程

发布于 4年前 浏览 17 项目主页 更新于 3年前

ackee|Antonio

GitHub licenseCI StatusPRs WelcomeDependency Statusbundlephobiabundlephobia

Antonio

使用 axios 的 HTTP 客户端HTTP 请求和 @ackee/petrus 用于将访问令牌添加到授权标头。

Table of contents


Installing

使用 yarn:

$ yarn add @ackee/antonio

使用 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

初始化 saga 处理程序生成器。 这应该与您的其他传奇一起传递。

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

请参阅 api 对象的可用属性

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

通过使用 authApi 对象下的方法,可以保证每个 HTTP 请求在其 Authorization 标头中都有一个访问令牌。

如果此时访问令牌不可用,则请求会因 take(ACCESS_TOKEN_AVAILABLE) 效果而暂停,并设置超时(如果启用)。 有关详细信息,请参阅 accessTokenUnavailableTimeout

请参阅 authApi 对象的可用属性

import { authApi } from 'Config/antonio';

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

    return response.data;
}

Shared defaults

尽管 apiauthApi 是作为独立的 axios 实例创建的,但它们共享相同的默认请求配置对象 - api.defaultsauthApi.defaults。 此问题/功能是由 axios 的实现方式引起的,@ackee/antonio 不会更改它。 当您在 api 创建的请求中也看到 Authorization 标头时,请不要感到惊讶。


API

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

此方法接收两个对象作为参数。

  • defaultRequestConfig: Object

    defaultRequestConfig 对象作为默认请求配置传递给 axios。

    可用属性

    • axios request config
    • additional props: js // `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

    customConfig 对象提供以下默认选项:

    {
        // 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

    apiauthApi 具有以下相同的属性:

    • 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

    内部传奇,主要用于与 @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

内置取消 API 请求的自定义 Saga 效果,请参阅文档

Utilities

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

默认配置中使用的实用程序,用于将不记名访问令牌值设置为 Authorization 标头。

ackee|Antonio

GitHub licenseCI StatusPRs WelcomeDependency Statusbundlephobiabundlephobia

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: js // `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.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文