index.ts 1.6 KB

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