index.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. type StorageType = "localStorage" | "sessionStorage";
  2. interface StorageKey {
  3. ban_pixel_type: "kwai_pixel" | "facebook_pixel";
  4. ban_cache_login: { pwd: string; user_phone: string };
  5. ban_pixel_id: string;
  6. ban_click_id: string;
  7. channel_code: string;
  8. ban_pop_type_0: string;
  9. ban_pop_type_1: string;
  10. pop_type_2: string;
  11. pop_type_3: string;
  12. wss: { node: string; address: string; port: number };
  13. }
  14. type Key = Extract<keyof StorageKey, string>;
  15. class CustomStorage {
  16. private type: StorageType;
  17. constructor(type: StorageType) {
  18. this.type = type;
  19. }
  20. /**
  21. * 设置
  22. */
  23. setKey<D extends StorageKey, V extends keyof StorageKey>(key: V, value: D[V]): void {
  24. const val = typeof value === "string" ? value : JSON.stringify(value);
  25. window[this.type]?.setItem(key, val);
  26. }
  27. /**
  28. * 获取
  29. */
  30. getKey<U extends Key>(key: U): StorageKey[U] {
  31. const result: any = window[this.type]?.getItem(key);
  32. try {
  33. return JSON.parse(result);
  34. } catch (e) {
  35. return result;
  36. }
  37. }
  38. /**
  39. * 移除
  40. */
  41. removeKey(key: Key): void {
  42. window[this.type]?.removeItem(key);
  43. }
  44. /**
  45. * key
  46. */
  47. key(index: number): Key | null {
  48. const k: any = window[this.type]?.key(index);
  49. return k;
  50. }
  51. /**
  52. * 清除
  53. */
  54. clear() {
  55. window[this.type]?.clear();
  56. }
  57. /**
  58. * 长度
  59. */
  60. get length() {
  61. return window[this.type]?.length;
  62. }
  63. }
  64. const Local = new CustomStorage("localStorage");
  65. const Session = new CustomStorage("sessionStorage");
  66. export { Local, Session };