axios-cache-data

axios 官方文档在这 axios
提示:被缓存后所有的响应信息都是初次请求状态,服务器删除或修改该数据都不会有感知。可以设置缓存时间或增加请求分组。
提示:代理 axios 对象实现缓存,取消 axios adapter 的实现方式。
1. 创建缓存类
const config: AxiosRequestConfig = {
baseURL: "xxx"
};
const instance: AxiosInstance = axios.create(config);
const cacheInstance: CacheAxios = CacheAxios.create({
adapter: (con) => instance.request(con),
maxAge: 1000 * 60 * 30,
valid(response: AxiosResponse): boolean {
return response.status === 200 && response.data.code === 200;
}
cacheInstance.clear();
cacheInstance.clear(config)
});
2. 创建缓存实例
import { http } from "lib/index";
const axiosInstance = http.proxy(,)
const axiosInstance = http()
3. 强制更新或使用缓存
import { http } from "lib/index";
const axiosInstance = http.proxy(,)
const axiosInstance = http()
axiosInstance.post(url, {}, { force: true });
axiosInstance.post(url, {}, { hit: true });
axiosInstance.clear()
const instance = axios.withCache(options);
instance.clear();
3.1. 序列化数据
import axios from "axios";
import { http } from "lib/index";
http({
message: {
}
});
4. 参数说明
export interface CacheInstance extends AxiosRequestConfig {
readonly maxAge?: number;
readonly key?: string;
readonly storage?: Storage;
readonly proxy?: Method[];
readonly enableCache?: boolean;
readonly prefix?: string;
readonly message?: {
serialization: Serialization; deserialization: Deserialization;
};
valid?(response: AxiosResponse): boolean;
generateKey?(key: string | undefined, url: string | undefined, method: any, header: any, params: string,
data: string): string;
}
axiosInstance.get(url, {
group: number | string,
hit: true,
force: true,
expire: number,
valid(res): boolean
...
})
4.1. 创建适配器的公共参数
| maxAge | 缓存最大时间 | 1000 _ 60 _ 60 (单位毫秒) |
| key | 生成 key 标识 | HTTP_CACHE_CACHE |
| storage | 缓存组件 | window.sessionStorage |
| prefix | 网络缓 key 存前缀 | AXIOS-CACHE |
| enableCache | 开启全局缓存 | false |
| generateKey | 生成一个请求唯一标识 key | |
| message | 消息序列化和反序列化 | |
| valid | 验证消息是否正确防止消息错误却被缓存 | |
| proxy | 指定缓存方法 | ["get", "post"] |
4.2. 每个请求的缓存参数
| hit | 是否需要命中缓存(优先级高于全局配置) |
| force | 强制走网络请求,并刷新缓存 |
| expire | 过期时间 |
| valid | 验证消息是否正确防止消息错误却被缓存 |
| group | 对请求分组,在清除缓存时可定向清除 |
5. 执行流程图
