chatStorage.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { isUniFrameWork } from '../../../utils/env';
  2. import { TUIGlobal } from '@tencentcloud/universal-api';
  3. interface IChatStorage {
  4. getChatStorage(key: string): any;
  5. setChatStorage(key: string, value: any): void;
  6. }
  7. class ChatStorage implements IChatStorage {
  8. private static instance: ChatStorage | null = null;
  9. private static CHAT_STORAGE_KEY: string = 'TUI_CHAT_STORAGE';
  10. private chatStorage: Record<string, any> | null = null;
  11. private constructor() {}
  12. public static getInstance(): ChatStorage {
  13. if (!ChatStorage.instance) {
  14. ChatStorage.instance = new ChatStorage();
  15. }
  16. return ChatStorage.instance;
  17. }
  18. public getChatStorage(key: string): any | undefined {
  19. if (!this.chatStorage) {
  20. this.chatStorage = this.getChatStorageFromLocalStorage();
  21. }
  22. if (key) {
  23. return this.chatStorage[key];
  24. } else {
  25. throw new Error('No key provided');
  26. }
  27. }
  28. public setChatStorage(key: string, value: any): void {
  29. if (!this.chatStorage) {
  30. this.chatStorage = this.getChatStorageFromLocalStorage();
  31. }
  32. this.chatStorage[key] = value;
  33. try {
  34. if (isUniFrameWork) {
  35. TUIGlobal.setStorageSync(ChatStorage.CHAT_STORAGE_KEY, JSON.stringify(this.chatStorage));
  36. } else {
  37. localStorage.setItem(ChatStorage.CHAT_STORAGE_KEY, JSON.stringify(this.chatStorage));
  38. }
  39. } catch (error) {
  40. throw new Error('Fail to set chat storage');
  41. }
  42. }
  43. private getChatStorageFromLocalStorage(): Record<string, any> {
  44. let chatStorageString: string = '';
  45. if (isUniFrameWork) {
  46. chatStorageString = TUIGlobal.getStorageSync(ChatStorage.CHAT_STORAGE_KEY) || '';
  47. } else {
  48. chatStorageString = localStorage.getItem(ChatStorage.CHAT_STORAGE_KEY) || '';
  49. }
  50. if (!chatStorageString) {
  51. return {};
  52. }
  53. try {
  54. this.chatStorage = JSON.parse(chatStorageString);
  55. } catch (error) {
  56. this.chatStorage = {};
  57. }
  58. return this.chatStorage as Record<string, any>;
  59. }
  60. }
  61. export default ChatStorage.getInstance();