Files
Situation-Awareness-Platfor…/src/utils/apiStorage.ts

92 lines
2.8 KiB
TypeScript
Raw Normal View History

2025-03-12 18:41:20 +08:00
import * as localForage from 'localforage';
export interface IRequestCache {
url: string; // 匹配 url必填
retry?: number; // 错误重试次数,非必填,默认为 0
method?: 'get' | 'post' | 'put' | 'delete'; // 接口请求方法,默认为 'get'
maxAge?: number; // 接口存储保留时间,默认为无限制
maxRows?: number; // 接口存储规格上限配置,默认 10 条
timeout?: number; // 前端判断接口超时时间,非必填,默认为无限制
degradedTime?: number; // 接口熔断时间非必填默认为30秒
withHeaders?: string[]; // 需要识别的 header非必填默认为空
ignoreUrlParams?: string[]; // 需要忽略的 url 参数非必填默认为空即会保存携带不同参数的所有url
withBodys?: string[]; // 区分请求体不同的请求
excludeStatusCode?: number[]; // 忽略的http状态码
}
export class StorageService {
instanceName = '';
instanceMap:any = {};
requestCacheList: IRequestCache[] = [];
SINGLE_SIZE_LIMIT = 1024 * 1024; //单条数据大小限制1M
TOTAL_NUMBER_LIMIT = 200; //单数据库实例存储条数不超过200
setRequestCacheList(requestCacheList: IRequestCache[]) {
this.requestCacheList = requestCacheList;
}
getRequestCacheList() {
return this.requestCacheList;
}
setInstanceName(name: string) {
this.instanceName = name;
}
getInstance(name: string) {
if (!this.instanceMap[name]) {
this.instanceMap[name] = localForage.createInstance({
name: `GitcodeDB_${name}`,
storeName: `GitcodeStore_${name}`,
});
}
return this.instanceMap[name];
}
setItem(key: string, value: any, instanceName = this.instanceName) {
const store = this.getInstance(instanceName);
this.chkAndCtlIntSize(store);
store.setItem(key, value);
}
getItem(key: string, instanceName = this.instanceName) {
const store = this.getInstance(instanceName);
return store.getItem(key);
}
removeItem(key: string, instanceName = this.instanceName) {
const store = this.getInstance(instanceName);
store.removeItem(key);
}
// 控制数据库总条数,超过后删除最早的一条
chkAndCtlIntSize(store: any, size = this.TOTAL_NUMBER_LIMIT) {
store.keys().then((keys: any) => {
const len = keys.length;
if (len > size) {
store.removeItem(keys[0]);
}
});
}
// 获取字符串占用存储大小
sizeOf(str: any) {
let total = 0;
let charCode;
str.split('').forEach((element: any, index: any) => {
charCode = str.charCodeAt(index);
if (charCode <= 0x007f) {
total += 1;
} else if (charCode <= 0x07ff) {
total += 2;
} else if (charCode <= 0xffff) {
total += 3;
} else {
total += 4;
}
});
return total;
}
}
export const storageService = new StorageService();