123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- type StorageType = "localStorage" | "sessionStorage";
- interface StorageKey {
- ban_pixel_type: "kwai_pixel" | "facebook_pixel";
- ban_cache_login: { pwd: string; user_phone: string };
- ban_pixel_id: string;
- ban_click_id: string;
- channel_code: string;
- ban_pop_type_0: string;
- ban_pop_type_1: string;
- pop_type_2: string;
- pop_type_3: string;
- wss: { node: string; address: string; port: number };
- }
- type Key = Extract<keyof StorageKey, string>;
- class CustomStorage {
- private type: StorageType;
- constructor(type: StorageType) {
- this.type = type;
- }
- /**
- * 设置
- */
- setKey<D extends StorageKey, V extends keyof StorageKey>(key: V, value: D[V]): void {
- const val = typeof value === "string" ? value : JSON.stringify(value);
- window[this.type]?.setItem(key, val);
- }
- /**
- * 获取
- */
- getKey<U extends Key>(key: U): StorageKey[U] {
- const result: any = window[this.type]?.getItem(key);
- try {
- return JSON.parse(result);
- } catch (e) {
- return result;
- }
- }
- /**
- * 移除
- */
- removeKey(key: Key): void {
- window[this.type]?.removeItem(key);
- }
- /**
- * key
- */
- key(index: number): Key | null {
- const k: any = window[this.type]?.key(index);
- return k;
- }
- /**
- * 清除
- */
- clear() {
- window[this.type]?.clear();
- }
- /**
- * 长度
- */
- get length() {
- return window[this.type]?.length;
- }
- }
- const Local = new CustomStorage("localStorage");
- const Session = new CustomStorage("sessionStorage");
- export { Local, Session };
|