You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Storage.js 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import { AsyncStorage } from 'react-native';
  2. /**
  3. * A Web Sorage API implementation used for polyfilling
  4. * {@code window.localStorage} and/or {@code window.sessionStorage}.
  5. * <p>
  6. * The Web Storage API is synchronous whereas React Native's builtin generic
  7. * storage API {@code AsyncStorage} is asynchronous so the implementation with
  8. * persistence is optimistic: it will first store the value locally in memory so
  9. * that results can be served synchronously and then persist the value
  10. * asynchronously. If an asynchronous operation produces an error, it's ignored.
  11. */
  12. export default class Storage {
  13. /**
  14. * Initializes a new {@code Storage} instance. Loads all previously
  15. * persisted data items from React Native's {@code AsyncStorage} if
  16. * necessary.
  17. *
  18. * @param {string|undefined} keyPrefix - The prefix of the
  19. * {@code AsyncStorage} keys to be persisted by this storage.
  20. */
  21. constructor(keyPrefix) {
  22. /**
  23. * The prefix of the {@code AsyncStorage} keys persisted by this
  24. * storage. If {@code undefined}, then the data items stored in this
  25. * storage will not be persisted.
  26. *
  27. * @private
  28. * @type {string}
  29. */
  30. this._keyPrefix = keyPrefix;
  31. if (typeof this._keyPrefix !== 'undefined') {
  32. // Load all previously persisted data items from React Native's
  33. // AsyncStorage.
  34. this._initialized = new Promise(resolve => {
  35. AsyncStorage.getAllKeys().then((...getAllKeysCallbackArgs) => {
  36. // XXX The keys argument of getAllKeys' callback may
  37. // or may not be preceded by an error argument.
  38. const keys
  39. = getAllKeysCallbackArgs[
  40. getAllKeysCallbackArgs.length - 1
  41. ].filter(key => key.startsWith(this._keyPrefix));
  42. AsyncStorage.multiGet(keys)
  43. .then((...multiGetCallbackArgs) => {
  44. // XXX The result argument of multiGet may or may not be
  45. // preceded by an errors argument.
  46. const result
  47. = multiGetCallbackArgs[
  48. multiGetCallbackArgs.length - 1
  49. ];
  50. const keyPrefixLength
  51. = this._keyPrefix && this._keyPrefix.length;
  52. // eslint-disable-next-line prefer-const
  53. for (let [ key, value ] of result) {
  54. key = key.substring(keyPrefixLength);
  55. // XXX The loading of the previously persisted data
  56. // items from AsyncStorage is asynchronous which
  57. // means that it is technically possible to invoke
  58. // setItem with a key before the key is loaded from
  59. // AsyncStorage.
  60. if (!this.hasOwnProperty(key)) {
  61. this[key] = value;
  62. }
  63. }
  64. resolve();
  65. });
  66. });
  67. });
  68. }
  69. }
  70. /**
  71. * Removes all keys from this storage.
  72. *
  73. * @returns {void}
  74. */
  75. clear() {
  76. for (const key of Object.keys(this)) {
  77. this.removeItem(key);
  78. }
  79. }
  80. /**
  81. * Returns the value associated with a specific key in this storage.
  82. *
  83. * @param {string} key - The name of the key to retrieve the value of.
  84. * @returns {string|null} The value associated with {@code key} or
  85. * {@code null}.
  86. */
  87. getItem(key) {
  88. return this.hasOwnProperty(key) ? this[key] : null;
  89. }
  90. /**
  91. * Returns the value associated with a specific key in this storage in an
  92. * async manner. This method is required for those cases where we need the
  93. * stored data but we're not sure yet whether the {@code Storage} is already
  94. * initialised or not - e.g. on app start.
  95. *
  96. * @param {string} key - The name of the key to retrieve the value of.
  97. * @private
  98. * @returns {Promise}
  99. */
  100. _getItemAsync(key) {
  101. return new Promise(
  102. resolve =>
  103. AsyncStorage.getItem(
  104. `${String(this._keyPrefix)}${key}`,
  105. (error, result) => resolve(result ? result : null)));
  106. }
  107. /**
  108. * Returns the name of the nth key in this storage.
  109. *
  110. * @param {number} n - The zero-based integer index of the key to get the
  111. * name of.
  112. * @returns {string} The name of the nth key in this storage.
  113. */
  114. key(n) {
  115. const keys = Object.keys(this);
  116. return n < keys.length ? keys[n] : null;
  117. }
  118. /**
  119. * Returns an integer representing the number of data items stored in this
  120. * storage.
  121. *
  122. * @returns {number}
  123. */
  124. get length() {
  125. return Object.keys(this).length;
  126. }
  127. /**
  128. * Removes a specific key from this storage.
  129. *
  130. * @param {string} key - The name of the key to remove.
  131. * @returns {void}
  132. */
  133. removeItem(key) {
  134. delete this[key];
  135. typeof this._keyPrefix === 'undefined'
  136. || AsyncStorage.removeItem(`${String(this._keyPrefix)}${key}`);
  137. }
  138. /**
  139. * Adds a specific key to this storage and associates it with a specific
  140. * value. If the key exists already, updates its value.
  141. *
  142. * @param {string} key - The name of the key to add/update.
  143. * @param {string} value - The value to associate with {@code key}.
  144. * @returns {void}
  145. */
  146. setItem(key, value) {
  147. value = String(value); // eslint-disable-line no-param-reassign
  148. this[key] = value;
  149. typeof this._keyPrefix === 'undefined'
  150. || AsyncStorage.setItem(`${String(this._keyPrefix)}${key}`, value);
  151. }
  152. }