Skip to content

FastAxios container ​

createFastAxios(options?, newInstance?) Create ​

Creates or updates the FastAxios configuration container.

ts
const fastAxios = createFastAxios({
	baseUrl: "https://api.example.com",
	timeout: 30_000,
	headers: { Authorization: "Bearer <token>" },
	requestCipher: false,
});
ParameterTypeDefaultDescription
options.baseUrlstring""Base URL used when creating Axios request instances.
options.timeoutnumber60000Request timeout in milliseconds.
options.headersRawAxiosHeaders{}Shared request headers; repeated configuration merges individual fields.
options.requestCipherbooleantrueEncryption/decryption switch used unless overridden for a request.
newInstancebooleanfalseWhen true, returns an independent container without writing the global singleton.

axiosUtil.request() always reads the global singleton. Independent containers do not automatically participate in requests.

Repeated singleton-mode createFastAxios() calls retain existing handlers and merge base options through setOptions().

useFastAxios() Instance ​

Returns the initialized global container. Throws Error before createFastAxios() has been called.

setOptions(options?) Options ​

Updates base options and returns the current container, preserving its concrete subtype in fluent TypeScript calls. Headers merge by field; other supplied values replace existing ones. Empty strings, 0, and false are valid.

addErrorCode() Errors ​

Adds or replaces error messages:

ts
fastAxios.addErrorCode(40101, "登录状态已失效");

fastAxios.addErrorCode({
	40102: "账号已停用",
	CUSTOM_ERROR: "自定义错误",
});

Supports HTTP status, Axios error, and Fast business codes. The single-code overload throws TypeError when message is absent.

createFastAxios Create ​

Creates or updates the global FastAxios container, or returns an independent container without changing the singleton.

Signature ​

ts
createFastAxios(options?: InitializeOptions, newInstance?: boolean): FastAxios;

Example ​

ts
import { createFastAxios } from "@fast-china/axios";

const result = createFastAxios({ baseUrl: "/api", timeout: 30_000, requestCipher: false });

Input ​

InputTypeRequired / defaultDescription
optionsInitializeOptionsOptionalBase URL, timeout, common headers, and global encryption/decryption switch.
newInstancebooleanOptional; defaults to falseWhen true, creates an independent container without affecting the global singleton.

Returns ​

ValueTypeDescription
resultFastAxiosGlobal singleton or newly created independent configuration container.

useFastAxios Instance ​

Gets the initialized global FastAxios singleton.

Signature ​

ts
useFastAxios(): FastAxios;

Example ​

ts
import { createFastAxios, useFastAxios } from "@fast-china/axios";

createFastAxios({ baseUrl: "/api" });
const result = useFastAxios();

Input ​

This method has no input parameters.

Returns ​

ValueTypeDescription
resultFastAxiosInitialized global container; throws Error when not initialized.

fastAxios.setOptions Options ​

Merges base configuration: headers merge by field, other explicit values replace existing ones.

Signature ​

ts
setOptions(options?: InitializeOptions): this;

Example ​

ts
import { createFastAxios } from "@fast-china/axios";

const fastAxios = createFastAxios({ baseUrl: "/api" }, true);

const result = fastAxios.setOptions({ timeout: 15_000, headers: { Authorization: "Bearer token" } });

Input ​

InputTypeRequired / defaultDescription
optionsInitializeOptionsOptional; defaults to {}Base options to update.

Returns ​

ValueTypeDescription
resultthisCurrent container, supporting fluent calls.

fastAxios.addErrorCode Errors ​

Adds or replaces one error message, or accepts an error-code map.

Signature ​

ts
addErrorCode(key: string | number, message: string): FastAxios;
addErrorCode(codes: Record<string | number, string>): FastAxios;

Example ​

ts
import { createFastAxios } from "@fast-china/axios";

const fastAxios = createFastAxios({ baseUrl: "/api" }, true);

fastAxios.addErrorCode(40101, "登录状态已失效");
const result = fastAxios.addErrorCode({ 40102: "账号已停用", CUSTOM_ERROR: "自定义错误" });

Input ​

InputTypeRequired / defaultDescription
keystring | numberRequired for the single-code overloadHTTP, Axios, or Fast business error code.
messagestringRequired for the single-code overloadMessage shown to the user.
codesRecord<string | number, string>Required for the map overloadBatch mapping of error codes to messages.

Returns ​

ValueTypeDescription
resultFastAxiosCurrent container, supporting fluent calls.

Internationalization and application translations ​

Since 2.0.7, the SDK includes Simplified Chinese (default), Traditional Chinese, and English without a UI or i18n framework dependency.

ts
import { createFastAxios } from "@fast-china/axios";
import type { FastAxiosLocale, FastAxiosLocaleSource, FastAxiosMessageKey, FastAxiosTranslate } from "@fast-china/axios";

let language: FastAxiosLocale = "zh-CN";
const locale: FastAxiosLocaleSource = () => language;
const appMessages: Partial<Record<FastAxiosMessageKey, string>> = { loading: "Please wait..." };
const translate: FastAxiosTranslate = (key, currentLocale, fallback) => (currentLocale === "en-US" ? (appMessages[key] ?? fallback) : fallback);

const fastAxios = createFastAxios({ locale, translate });
language = "en-US";
fastAxios.setOptions({ locale: "zh-TW", translate: null });

Read the application language through locale and delegate translate to your synchronous translation function. Return a translation only when the key exists; otherwise return undefined, null, or fallback.

  • FastAxiosLocale: "zh-CN" | "zh-TW" | "en-US". FastAxiosLocaleSource also accepts a synchronous string getter. Unsupported values fall back to zh-CN; locale aliases are not normalized automatically.
  • FastAxiosTranslate: (key: FastAxiosMessageKey, locale: FastAxiosLocale, fallback: string) => string | null | undefined. FastAxiosMessageKey includes string HTTP status codes such as "400", original Axios codes such as "ERR_NETWORK", default, offLine, fileDownloadError, loading, and SDK confirmation keys.
  • Locale and translations are resolved at message lookup time without an in-flight snapshot. Empty strings are valid. A throwing translator falls back to built-in text in the selected language; a throwing locale getter falls back to Simplified Chinese. Neither replaces request errors. Use setOptions({ translate: null }) to remove the callback; omitted or undefined options preserve it.
  • Built-in errorCode values follow the language. Explicit assignments and addErrorCode() overrides retain priority. Server messages, explicit loadingText, and explicit confirmation button text bypass translation.
  • Default Loading text, error hints, RESTful validation errors, and uni confirmation titles/buttons are localized. Browser confirmation buttons remain browser-controlled. Server text, native Axios/uni diagnostics, original cancellation reasons, and developer configuration diagnostics remain unchanged.
  • HTTP/network requests reject with the same AxiosError, preserving code, message, config, request, and response. Cancellation still rejects, remains detectable through axios.isCancel(), and produces no extra notification. SDK-created business errors localize the message and retain ERR_BAD_RESPONSE.
  • Headers are not changed automatically. For language-dependent server responses, configure the language header and clear cached responses, or distinguish languages in URL query parameters. Independent containers retain independent locale/translation state; requests still use the global singleton.

fastAxios.t(key) ​

ts
t(key: FastAxiosMessageKey): string;

Returns SDK text through the translation callback and fallback rules above. It does not apply addErrorCode() overrides; read fastAxios.errorCode[code] for the final error-code text.

App and mini-program boundaries ​

Internationalization uses ordinary objects, Object.keys, Object.defineProperty, and synchronous callbacks, without depending on Intl, DOM APIs, or browser storage. See the uni-app JavaScript runtime documentation.

The uni.showModal documentation limits mini-program confirmation/cancellation labels to four characters. Built-in English uses OK / Back. Custom translations and explicit button labels must also respect the target platform limit; the SDK does not truncate caller text.

Current SDK artifacts target ES2022. Older systems/base libraries still require appropriate consumer transpilation and runtime support. The existing uni adapter requires btoa for Basic Auth; without it, auth rejects with ERR_BAD_OPTION_VALUE. H5 success does not establish App/mini-program compatibility.

Controlled uni requests verified ordinary requests, dynamic language selection, and network error text without window, document, navigator, Intl, crypto, TextEncoder, URL, URLSearchParams, Blob, FormData, or AbortController. These tests do not replace target builds or device validation and do not cover every dependency initialization path.