dataStorage.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. interface IStorage {
  2. getItem: (key: string) => string | null;
  3. setItem: (key: string, value: string) => void;
  4. }
  5. /**
  6. * Class for storing data to local storage if available or in-memory storage otherwise
  7. */
  8. export class DataStorage {
  9. private static _Storage: IStorage = DataStorage._GetStorage();
  10. private static _GetStorage(): IStorage {
  11. try {
  12. localStorage.setItem("test", "");
  13. localStorage.removeItem("test");
  14. return localStorage;
  15. }
  16. catch {
  17. const inMemoryStorage: { [key: string]: string } = {};
  18. return {
  19. getItem: (key) => {
  20. const value = inMemoryStorage[key];
  21. return value === undefined ? null : value;
  22. },
  23. setItem: (key, value) => {
  24. inMemoryStorage[key] = value;
  25. }
  26. };
  27. }
  28. }
  29. /**
  30. * Reads a string from the data storage
  31. * @param key The key to read
  32. * @param defaultValue The value if the key doesn't exist
  33. * @returns The string value
  34. */
  35. public static ReadString(key: string, defaultValue: string): string {
  36. const value = this._Storage.getItem(key);
  37. return (value !== null ? value : defaultValue);
  38. }
  39. /**
  40. * Writes a string to the data storage
  41. * @param key The key to write
  42. * @param value The value to write
  43. */
  44. public static WriteString(key: string, value: string): void {
  45. this._Storage.setItem(key, value);
  46. }
  47. /**
  48. * Reads a boolean from the data storage
  49. * @param key The key to read
  50. * @param defaultValue The value if the key doesn't exist
  51. * @returns The boolean value
  52. */
  53. public static ReadBoolean(key: string, defaultValue: boolean): boolean {
  54. const value = this._Storage.getItem(key);
  55. return (value !== null ? (value === "true") : defaultValue);
  56. }
  57. /**
  58. * Writes a boolean to the data storage
  59. * @param key The key to write
  60. * @param value The value to write
  61. */
  62. public static WriteBoolean(key: string, value: boolean) {
  63. this._Storage.setItem(key, value ? "true" : "false");
  64. }
  65. /**
  66. * Reads a number from the data storage
  67. * @param key The key to read
  68. * @param defaultValue The value if the key doesn't exist
  69. * @returns The number value
  70. */
  71. public static ReadNumber(key: string, defaultValue: number): number {
  72. const value = this._Storage.getItem(key);
  73. return (value !== null ? parseFloat(value) : defaultValue);
  74. }
  75. /**
  76. * Writes a number to the data storage
  77. * @param key The key to write
  78. * @param value The value to write
  79. */
  80. public static WriteNumber(key: string, value: number) {
  81. this._Storage.setItem(key, value.toString());
  82. }
  83. }