FastAxios container
createFastAxios(options?, newInstance?) Create
Creates or updates the FastAxios configuration container.
const fastAxios = createFastAxios({
baseUrl: "https://api.example.com",
timeout: 30_000,
headers: { Authorization: "Bearer <token>" },
requestCipher: false,
});| Parameter | Type | Default | Description |
|---|---|---|---|
options.baseUrl | string | "" | Base URL used when creating Axios request instances. |
options.timeout | number | 60000 | Request timeout in milliseconds. |
options.headers | RawAxiosHeaders | {} | Shared request headers; repeated configuration merges individual fields. |
options.requestCipher | boolean | true | Encryption/decryption switch used unless overridden for a request. |
newInstance | boolean | false | When 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:
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
createFastAxios(options?: InitializeOptions, newInstance?: boolean): FastAxios;Example
import { createFastAxios } from "@fast-china/axios";
const result = createFastAxios({ baseUrl: "/api", timeout: 30_000, requestCipher: false });Input
| Input | Type | Required / default | Description |
|---|---|---|---|
options | InitializeOptions | Optional | Base URL, timeout, common headers, and global encryption/decryption switch. |
newInstance | boolean | Optional; defaults to false | When true, creates an independent container without affecting the global singleton. |
Returns
| Value | Type | Description |
|---|---|---|
result | FastAxios | Global singleton or newly created independent configuration container. |
useFastAxios Instance
Gets the initialized global FastAxios singleton.
Signature
useFastAxios(): FastAxios;Example
import { createFastAxios, useFastAxios } from "@fast-china/axios";
createFastAxios({ baseUrl: "/api" });
const result = useFastAxios();Input
This method has no input parameters.
Returns
| Value | Type | Description |
|---|---|---|
result | FastAxios | Initialized global container; throws Error when not initialized. |
fastAxios.setOptions Options
Merges base configuration: headers merge by field, other explicit values replace existing ones.
Signature
setOptions(options?: InitializeOptions): this;Example
import { createFastAxios } from "@fast-china/axios";
const fastAxios = createFastAxios({ baseUrl: "/api" }, true);
const result = fastAxios.setOptions({ timeout: 15_000, headers: { Authorization: "Bearer token" } });Input
| Input | Type | Required / default | Description |
|---|---|---|---|
options | InitializeOptions | Optional; defaults to {} | Base options to update. |
Returns
| Value | Type | Description |
|---|---|---|
result | this | Current container, supporting fluent calls. |
fastAxios.addErrorCode Errors
Adds or replaces one error message, or accepts an error-code map.
Signature
addErrorCode(key: string | number, message: string): FastAxios;
addErrorCode(codes: Record<string | number, string>): FastAxios;Example
import { createFastAxios } from "@fast-china/axios";
const fastAxios = createFastAxios({ baseUrl: "/api" }, true);
fastAxios.addErrorCode(40101, "登录状态已失效");
const result = fastAxios.addErrorCode({ 40102: "账号已停用", CUSTOM_ERROR: "自定义错误" });Input
| Input | Type | Required / default | Description |
|---|---|---|---|
key | string | number | Required for the single-code overload | HTTP, Axios, or Fast business error code. |
message | string | Required for the single-code overload | Message shown to the user. |
codes | Record<string | number, string> | Required for the map overload | Batch mapping of error codes to messages. |
Returns
| Value | Type | Description |
|---|---|---|
result | FastAxios | Current 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.
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".FastAxiosLocaleSourcealso accepts a synchronous string getter. Unsupported values fall back tozh-CN; locale aliases are not normalized automatically.FastAxiosTranslate:(key: FastAxiosMessageKey, locale: FastAxiosLocale, fallback: string) => string | null | undefined.FastAxiosMessageKeyincludes 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
errorCodevalues follow the language. Explicit assignments andaddErrorCode()overrides retain priority. Server messages, explicitloadingText, 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, andresponse. Cancellation still rejects, remains detectable throughaxios.isCancel(), and produces no extra notification. SDK-created business errors localize the message and retainERR_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)
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.
