longmo-axios-extensions
v0.2.2
Published
make axios great again
Downloads
4
Maintainers
Readme
longmo-axios-extensions
一个非侵入式、简单、可靠的 axios 扩展集合
扩展列表
注意:由于 axios v0.19.0 存在自定义配置错误,不支持该版本。详见 https://github.com/axios/axios/pull/2207。
- cacheAdapterEnhancer - 使请求可缓存
- throttleAdapterEnhancer - 自动节流 GET 请求
- retryAdapterEnhancer - 在请求失败时自动重试指定次数
安装
pnpm i longmo-axios-extensions -S或者
npm i longmo-axios-extensions -S或者
yarn add longmo-axios-extensions或者
<!-- 在浏览器中作为 window['longmo-axios-extensions'] 使用 -->
<script src="https://unpkg.com/longmo-axios-extensions/dist/longmo-axios-extensions.min.js"></script>使用方法
import axios from 'axios';
import {cacheAdapterEnhancer, throttleAdapterEnhancer} from 'longmo-axios-extensions';
// 使用节流和缓存增强器增强原始 axios 适配器
const http = axios.create({
baseURL: '/',
headers: {'Cache-Control': 'no-cache'},
adapter: throttleAdapterEnhancer(cacheAdapterEnhancer(axios.getAdapter(axios.defaults.adapter)))
});启用日志记录
强烈建议在开发环境中启用请求日志记录(默认禁用)。
如果你不需要,可以在调用插件之前设置:
window.process = {...window.process, env: {LOGGER_LEVEL: "warn"}};浏览器环境 (webpack)
new webpack.DefinePlugin({
'process.env.LOGGER_LEVEL': JSON.stringify('info')
})// vite.config.js
import {defineConfig} from 'vite';
export default defineConfig(({mode}) => {
return {
define: {
'process.env.LOGGER_LEVEL': JSON.stringify(mode === 'development' ? 'info' : 'error')
}
};
});// rsbuild.config.js
export default ({command}) => {
return {
source: {
define: {
'process.env.LOGGER_LEVEL': JSON.stringify(command === 'dev' ? 'info' : 'error')
}
}
};
};Node.js 环境
// package.json
"scripts": {
"start": "cross-env LOGGER_LEVEL=info node server.js"
}API
cacheAdapterEnhancer
使 axios 请求可缓存
cacheAdapterEnhancer(adapter: AxiosAdapter, options: Options): AxiosAdapter其中 adapter 是遵循 axios 适配器标准 的 axios 适配器,options 是可选的缓存配置对象:
| 参数 | 类型 | 默认值 | 描述 |
|-------------------|-------------|-------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|
| enabledByDefault | boolean | true | 为所有请求启用缓存,无需在请求配置中显式定义(例如 cache: true) |
| cacheFlag | string | 'cache' | 配置在 axios 请求中显式定义缓存使用的键(标志) |
| defaultCache | CacheLike | new LRUCache({ maxAge: FIVE_MINUTES, max: 100 }) | 默认用于存储请求的 CacheLike 实例,除非你在请求配置中定义了自定义缓存 |
cacheAdapterEnhancer 增强给定的适配器并返回一个新的可缓存适配器,因此你可以将其与其他增强器组合使用,例如 throttleAdapterEnhancer。
基本用法
import axios from 'axios';
import {cacheAdapterEnhancer} from 'longmo-axios-extensions';
const http = axios.create({
baseURL: '/',
headers: {'Cache-Control': 'no-cache'},
// 默认启用缓存
adapter: cacheAdapterEnhancer(axios.getAdapter(axios.defaults.adapter))
});
http.get('/users'); // 发起真实的 HTTP 请求
http.get('/users'); // 使用之前请求的缓存响应,无需发起真实 HTTP 请求
http.get('/users', {cache: false}); // 手动禁用缓存,发起真实 HTTP 请求自定义缓存标志
const http = axios.create({
baseURL: '/',
headers: {'Cache-Control': 'no-cache'},
// 禁用默认缓存并设置缓存标志
adapter: cacheAdapterEnhancer(axios.getAdapter(axios.defaults.adapter), {
enabledByDefault: false,
cacheFlag: 'useCache'
})
});
http.get('/users'); // 默认缓存已禁用,发起真实 HTTP 请求
http.get('/users', {useCache: true}); // 使请求可缓存(由于是第一次请求,会发起真实 HTTP 请求)
http.get('/users', {useCache: true}); // 使用之前请求的缓存响应自定义缓存类型声明
注意:如果你使用自定义缓存标志和 TypeScript,可能需要添加以下类型声明:
import {ICacheLike} from 'longmo-axios-extensions';
declare module 'axios' {
interface AxiosRequestConfig {
// 如果你的 cacheFlag 设置为 'useCache'
useCache?: boolean | ICacheLike<any>;
}
}高级用法
除了通过 cacheAdapterEnhancer 配置请求外,我们还可以通过配置每个单独的请求来享受更高级的功能。
import axios from 'axios';
import {cacheAdapterEnhancer, Cache} from 'longmo-axios-extensions';
const http = axios.create({
baseURL: '/',
headers: {'Cache-Control': 'no-cache'},
// 禁用默认缓存
adapter: cacheAdapterEnhancer(axios.getAdapter(axios.defaults.adapter), {enabledByDefault: false})
});
http.get('/users', {cache: true}); // 使请求可缓存(由于是第一次请求,会发起真实 HTTP 请求)
// 手动定义一个缓存
const cacheA = new Cache();
// 或者一个类缓存实例
const cacheB = {
get() {/*...*/},
set() {/*...*/},
del() {/*...*/}
};
// 由于使用了不同的缓存,会发起两个实际的请求
http.get('/users', {cache: cacheA});
http.get('/users', {cache: cacheB});
// 由于配置了强制更新,会发起实际请求并缓存
http.get('/users', {cache: cacheA, forceUpdate: true});注意:如果你使用 TypeScript,不要忘记启用 "esModuleInterop": true 和 "allowSyntheticDefaultImports": true 以获得更好的开发体验。
throttleAdapterEnhancer
在指定的阈值毫秒内,GET 请求最多只发起一次
throttleAdapterEnhancer(adapter: AxiosAdapter, options: Options): AxiosAdapter其中 adapter 是遵循 axios 适配器标准 的 axios 适配器,options 是可选的节流配置对象:
| 参数 | 类型 | 默认值 | 描述 | |-----------|-----------|--------------------------------|-------------------------------------------------------| | threshold | number | 1000 | 限制请求调用的毫秒数 | | cache | CacheLike | new LRUCache({ max: 10 }) | 用于存储节流请求的 CacheLike 实例 |
我们建议将 throttleAdapterEnhancer 与 cacheAdapterEnhancer 一起使用,以获得最大的缓存优势。
注意:除了 GET 之外的 POST 和其他方法不受影响。
throttleAdapterEnhancer(cacheAdapterEnhancer(axios.getAdapter(axios.defaults.adapter)))查看 David Corbacho 的文章 了解更多关于节流的详细信息以及它与防抖的区别。
基本用法
import axios from 'axios';
import {throttleAdapterEnhancer} from 'longmo-axios-extensions';
const http = axios.create({
baseURL: '/',
headers: {'Cache-Control': 'no-cache'},
adapter: throttleAdapterEnhancer(axios.getAdapter(axios.defaults.adapter), {threshold: 2 * 1000})
});
http.get('/users'); // 发起真实 HTTP 请求
http.get('/users'); // 从缓存响应
http.get('/users'); // 从缓存响应
setTimeout(() => {
http.get('/users'); // 2秒后,再次发起真实请求
}, 2 * 1000);retryAdapterEnhancer
在请求失败时重试指定次数
retryAdapterEnhancer(adapter: AxiosAdapter, options: Options): AxiosAdapter其中 adapter 是遵循 axios 适配器标准 的 axios 适配器,options 是可选的配置对象:
| 参数 | 类型 | 默认值 | 描述 | |-------|--------|--------|--------------------------| | times | number | 2 | 全局设置失败请求的重试次数 |
基本用法
import axios from 'axios';
import {retryAdapterEnhancer} from 'longmo-axios-extensions';
const http = axios.create({
baseURL: '/',
headers: {'Cache-Control': 'no-cache'},
adapter: retryAdapterEnhancer(axios.getAdapter(axios.defaults.adapter))
});
// 如果此请求失败,将重试两次
http.get('/users');
// 你也可以为特定请求设置重试次数
http.get('/special', {retryTimes: 3});