dataStorage.js 2.5 KB

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